From riklaunim at gmail.com Thu Jun 1 00:04:41 2006 From: riklaunim at gmail.com (=?ISO-8859-2?Q?piotr_mali=F1ski?=) Date: Wed, 31 May 2006 23:04:41 +0100 Subject: is a wiki engine based on a cvs/svn a good idea? Message-ID: <1f7f7cf70605311504q1bb9660em2a8e6dcefd01e49d@mail.gmail.com> I'm planning to wite a fully featured wiki in Python in one of frameworks. I've seen some notes about wiki/documentation management scripts that use SVN as a data storage/versioning. I've been using SVN a bit but I don't know if it's a good idea to use it in a wiki engine. Pro: versioning / diffs, Cons: you need your own svn/cvs repository, can pyLucene or Xapwrap index this? From vinay_sajip at yahoo.co.uk Thu Jun 1 00:05:13 2006 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 31 May 2006 15:05:13 -0700 Subject: logging In-Reply-To: References: <1148426018.334087.124160@i40g2000cwc.googlegroups.com> <1148577240.250304.116360@j55g2000cwa.googlegroups.com> <1149005605.819519.242350@j55g2000cwa.googlegroups.com> Message-ID: <1149113113.083677.235570@i39g2000cwa.googlegroups.com> ibr at radix50.net wrote: > Hello Vinay, > > Hmm, log1 decides once whether to print an event, and after that it gets > printed in log1 and all its ancestors, regardless of their level? I find > this quite counter-intuitive. I'd instead expect that each logger > decides whether to print an event according to its own level. Could you > give an example why one would want the python behavior? Loggers are hierarchical for a reason - not just randomly named channels. Just as it is generally useful to develop a system by modularising it into subsystems, packages, modules, etc. so it is useful when logging to follow a parallel hierarchy. The audiences for the logging events are orthogonal to the events themselves, and the way the logging module is organised reflects good practice as determined by practical experience over a period of time. The approach you're questioning is not specific to Python - log4j (which inspired Python's logging), and the logging built into Java 1.4, also work this way. Practically, this makes configuration a lot simpler; if I want to log everything to console, I just attach a handler to the root logger, and I never have to worry about attaching to every single logger. (Logger names are generally not cast in stone - I might break down a module's logic into smaller pieces and thus introduce new logger names to describe events in the refactored module. I certainly don't want to change my logging configuration every time I refactor my code.) May I suggest you review the log4j documentation to get a better exposition of the principles which govern the design of such logging systems. From ippisl at gmail.com Thu Jun 1 00:29:11 2006 From: ippisl at gmail.com (ippisl at gmail.com) Date: 31 May 2006 15:29:11 -0700 Subject: OT: Search for python in Norway In-Reply-To: <1149108651.205786.99100@j55g2000cwa.googlegroups.com> References: <1149108651.205786.99100@j55g2000cwa.googlegroups.com> Message-ID: <1149114551.858491.231890@i40g2000cwc.googlegroups.com> your search for python refers for python=snake. you should look for "python programming". cyberco wrote: > Although the climate wouldn't make you think so, but searching for > python is hot in Norway: > > http://www.google.com/trends?q=python&ctab=1&geo=all&date=all > > I wonder what the explanation could be. > > Btw: Java seems to be all the rage in India :) > http://www.google.com/trends?q=java&ctab=1&geo=all&date=all From gdamjan at gmail.com Thu Jun 1 00:33:54 2006 From: gdamjan at gmail.com (Damjan) Date: Thu, 01 Jun 2006 00:33:54 +0200 Subject: is a wiki engine based on a cvs/svn a good idea? References: Message-ID: <447e19d2$0$15788$14726298@news.sunsite.dk> > I'm planning to wite a fully featured wiki in Python in one of > frameworks. I've seen some notes about wiki/documentation management > scripts that use SVN as a data storage/versioning. Cool > I've been using SVN a bit but I don't know if it's a good idea to use > it in a wiki engine. Pro: versioning / diffs, Cons: you need your own > svn/cvs repository, can pyLucene or Xapwrap index this? You can certanly index the svn checkout if nothing else. -- damjan From bdesth.quelquechose at free.quelquepart.fr Thu Jun 1 04:14:20 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 01 Jun 2006 04:14:20 +0200 Subject: is a wiki engine based on a cvs/svn a good idea? In-Reply-To: References: Message-ID: <447e1dfc$0$20866$626a54ce@news.free.fr> piotr maliski a ?crit : > I'm planning to wite a fully featured wiki in Python Then first have a look at both moinmoin and Trac. Good part of the job is already done. > in one of > frameworks. I've seen some notes about wiki/documentation management > scripts that use SVN as a data storage/versioning. > I've been using SVN a bit but I don't know if it's a good idea to use > it in a wiki engine. This has been discussed for Trac, cf: http://projects.edgewall.com/trac/wiki/TighterSubversionIntegration http://projects.edgewall.com/trac/wiki/WhySQLite > Pro: versioning / diffs, > Cons: you need your own svn/cvs repository, > can pyLucene or Xapwrap index this? From jcb at iteris.com Thu Jun 1 00:53:30 2006 From: jcb at iteris.com (Metalone) Date: 31 May 2006 15:53:30 -0700 Subject: ctypes pointers and SendMessage Message-ID: <1149116010.351538.258990@g10g2000cwb.googlegroups.com> I would like to call windll.user32.SendMessageA(hwnd, win32con.WM_COMMAND, wParam, lParam) where lParam represents a pointer to an object. And also convert this pointer back to an object reference inside of wnd_proc def wnd_proc(hwnd, msg, wParam, lParam): So something like this: class X(Structure): def __init__(self, x): self.v = x x = X(1) windll.user32.SendMessageA(hwnd, WM_COMMAND, 4000, addressof(x)) def wnd_proc(hwnd, msg, wParam, lParam): if msg == WM_COMMAND and wParam == 4000): x = X.from_address(lParam) print x.v Unfortunately, this does not work. Also to my surprise the following does not work: x1 = X(1) x2 = X.from_address(addressof(x1)) addressof(x1) == addressof(x2) --> True but x2.v --> 'object has no attribute v' x1.v --> 1 Also this does not work as I expect. p = pointer(x) p[0].v --> 'object has no attribute v'. What am I doing wrong? From mateus.justino at gmail.com Thu Jun 1 01:09:32 2006 From: mateus.justino at gmail.com (mateus) Date: 31 May 2006 16:09:32 -0700 Subject: Variable name has a typo, but code still works. Why? References: <1149082236.151844.99600@u72g2000cwu.googlegroups.com> <1149083447.370584.197070@f6g2000cwb.googlegroups.com> Message-ID: <1149116972.201718.155660@h76g2000cwa.googlegroups.com> Well, one by one I checked for the presence of both sessions and session in the globals dictionary (within showReport(), but outside of the loops). Neither one of them existed previously, thus and I received the exception about them not being found: File "/home/mjpl/hct/repository/hct/tutoo.py", line 219, in loadNext self.loadStage(self.cur+1) File "/home/mjpl/hct/repository/hct/tutoo.py", line 195, in loadStage self.stageFrame.show() File "/home/mjpl/hct/repository/hct/stages/resultadoframe/resultadoframe.py", line 17, in show self.listView.showReport() File "/home/mjpl/hct/repository/hct/widgets/deviceview.py", line 54, in showReport print globals()['session'] KeyError: 'session' So, I tried using other variable names for the outer and inner loops with the only difference of one letter. I then got the expected message about the variable name not being encountered. I returned the variable names to 'sessions' and 'session' respectively, and I got the same error about the name 'session' not being founded. I can only assume that there was some type of cache problem. Could it have been in the .pyc? I thought that was recompiled every time a .py is run/set to be interpreted. I'm sure I got that last sentence wrong. hwiechers at gmail.com wrote: > mateus wrote: > > print "hello world" > > > > I have a nested loop where the outer loop iterates over key value pairs > > of a dictionary and the inner loop iterates over a list each list of > > which is a mapped value from the dictionary > > > > def showReport(self): > > for dev, sessions in self.logger.items(): > > for tree in session: > > self.addTestItem(self, tree) > > > > What I don't understand is why this executes w/o any problems when > > "sessions" was spelled as plural (sessionS) while later being spelled > > in the singular (session). > > > > Is there some type of name resolution of local variables where Python > > makes assumptions? > > I've never heard of a rule disregarding ending 's'es and I really doubt > one > exists. > > Are you sure session isn't a global variable? You can check using > globals(). From jmcmonagle at velseis.com.au Thu Jun 1 01:19:00 2006 From: jmcmonagle at velseis.com.au (John McMonagle) Date: Thu, 01 Jun 2006 09:19:00 +1000 Subject: Tkinter question In-Reply-To: <9583ed900605310837q57eb8b76h6ac5e9c435bf885@mail.gmail.com> References: <9583ed900605310837q57eb8b76h6ac5e9c435bf885@mail.gmail.com> Message-ID: <1149117540.26711.9.camel@kuepper.vels-int.com.au> On Wed, 2006-05-31 at 11:37 -0400, david brochu jr wrote: > I am trying to create a GUI that will display a new window with > information about my program when the user clicks on the info button > (a green "i" bitmap). So far all I can get my program to do is show > the new window (using Toplevel() ) when the program loads, not when > the user presses the information bitmap. I think it has something to > do with my command for the information button. Anyone have any ideas > or have a GOOD resource that they could point me to? > Indeed the problem is to do with your command for the information button. Keeping it in your coding style, change it to: self.info_bttn["command"] = self.info Regards, John > -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. From go at away.com Thu Jun 1 01:24:01 2006 From: go at away.com (3rdshiftcoder) Date: Wed, 31 May 2006 23:24:01 GMT Subject: beginner: using parameter in functions Message-ID: hi- i am having trouble using parameter values in my function and to be honest a little trouble with member variables. i am trying to pass in the argument 'd' representing delete. what the code will do is if it is 'd' it will make a delete query template string. if it is an 'i' then insert query etc. this is the results of my attempt to print the contents of the parameter values. <__main__.getQryStr instance at 0x01151D50> ('d',) me mad (and on a side note if i dont include the *args i get an invalid number of parameters supplied message.) why is it returning the value in this format ('d',) ? i cant get x == d i guess that value 'd' is stored in a tuple and i'd like to get it out of there. so basically the function returns nope as it stands python is sure different from other languages i have used. thanks for any help, jim class getQryStr: def __init__(self,op): print op self.x = 'd' def returnStr(x,*args): print '%s %s me mad' % (x,args) if x == 'd': s = Template("delete from columndef where tblid = $tblid and colname = $colname") else: return 'nope' #this else is just for illustration and testing d = dict(tblid=t.tblid.getText(), colname=t.colName.getText()) print s.substitute(d) return s def delqry(self): createfldobj = getQryStr('d') s = createfldobj.returnStr('d') From eurleif at ecritters.biz Thu Jun 1 01:28:09 2006 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Wed, 31 May 2006 19:28:09 -0400 Subject: TSV to HTML In-Reply-To: <1149098823.979329.9220@f6g2000cwb.googlegroups.com> References: <1149098823.979329.9220@f6g2000cwb.googlegroups.com> Message-ID: <447e268a$0$3699$4d3efbfe@news.sover.net> Brian wrote: > I was wondering if anyone here on the group could point me in a > direction that would expllaing how to use python to convert a tsv file > to html. I have been searching for a resource but have only seen > information on dealing with converting csv to tsv. Specifically I want > to take the values and insert them into an html table. import csv from xml.sax.saxutils import escape def tsv_to_html(input_file, output_file): output_file.write('\n') for row in csv.reader(input_file, 'excel-tab'): output_file.write('') for col in row: output_file.write('' % escape(col)) output_file.write('\n') output_file.write('
%s
') Usage example: >>> from cStringIO import StringIO >>> input_file = StringIO('"foo"\t"bar"\t"baz"\n' ... '"qux"\t"quux"\t"quux"\n') >>> output_file = StringIO() >>> tsv_to_html(input_file, output_file) >>> print output_file.getvalue()
foobarbaz
quxquuxquux
From tjreedy at udel.edu Thu Jun 1 01:34:52 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 31 May 2006 19:34:52 -0400 Subject: OT: Search for python in Norway References: <1149108651.205786.99100@j55g2000cwa.googlegroups.com> <1149114551.858491.231890@i40g2000cwc.googlegroups.com> Message-ID: wrote in message news:1149114551.858491.231890 at i40g2000cwc.googlegroups.com... > your search for python refers for python=snake. It combines both, but spikes are definately snakey. > you should look for "python programming". I tried that, and Google missed the Nokia article it found with python alone. Also, South Africa and India are hottest countries with their normalization. http://www.google.com/trends?q=python+programming&ctab=1&geo=all&date=all tjr From pydecker at gmail.com Thu Jun 1 01:35:37 2006 From: pydecker at gmail.com (Peter Decker) Date: Wed, 31 May 2006 19:35:37 -0400 Subject: using import * with GUIs? In-Reply-To: References: Message-ID: On 5/31/06, John Salerno wrote: > I guess if I'm going to learn a GUI, I might as well jump right into > wxPython from the beginning. May I recommend that you take a look at the Dabo project? While they have a full application framework for creating database applications, you can easily just use the dabo.ui module, which wraps wxPython. This eliminates most of the C++ cruft that wxPython inherited from wxWidgets, and makes for a much more Pythonic experience. I worked with wxPython for a couple of years, and looked at Dabo based on a recommendation on the wxPython list. Since then, I haven't written a single app using raw wxPython; I use the dabo.ui module for all my GUI applications. It gives you all the advantages of wxPython, but it just works better. -- # p.d. From jmcmonagle at velseis.com.au Thu Jun 1 01:57:13 2006 From: jmcmonagle at velseis.com.au (John McMonagle) Date: Thu, 01 Jun 2006 09:57:13 +1000 Subject: beginner: using parameter in functions In-Reply-To: References: Message-ID: <1149119833.26711.12.camel@kuepper.vels-int.com.au> On Wed, 2006-05-31 at 23:24 +0000, 3rdshiftcoder wrote: > hi- > > i am having trouble using parameter values in my function and to be honest a > little trouble with > member variables. i am trying to pass in the argument 'd' representing > delete. > what the code will do is if it is 'd' it will make a delete query template > string. > if it is an 'i' then insert query etc. > > this is the results of my attempt to print the contents of the parameter > values. > <__main__.getQryStr instance at 0x01151D50> ('d',) me mad > > > (and on a side note if i dont include the *args i get an invalid number of > parameters supplied message.) > why is it returning the value in this format ('d',) ? > i cant get x == d > i guess that value 'd' is stored in a tuple and i'd like to get it out of > there. > > so basically the function returns nope as it stands > > python is sure different from other languages i have used. > > thanks for any help, > jim > Try, the following: class getQryStr: def __init__(self,op): print op self.x = 'd' def returnStr(self, *args): print '%s %s me mad' % (self.x,args) if self.x == 'd': s = Template("delete from columndef where tblid = $tblid and colname = $colname") else: return 'nope' #this else is just for illustration and testing d = dict(tblid=t.tblid.getText(), colname=t.colName.getText()) print s.substitute(d) return s Regards, John -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. From sjmachin at lexicon.net Thu Jun 1 02:21:05 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 01 Jun 2006 10:21:05 +1000 Subject: beginner: using parameter in functions In-Reply-To: References: Message-ID: <447e32f3@news.eftel.com> On 1/06/2006 9:24 AM, 3rdshiftcoder wrote: > hi- > > i am having trouble using parameter values in my function and to be honest a > little trouble with > member variables. i am trying to pass in the argument 'd' representing > delete. > what the code will do is if it is 'd' it will make a delete query template > string. > if it is an 'i' then insert query etc. > > this is the results of my attempt to print the contents of the parameter > values. > <__main__.getQryStr instance at 0x01151D50> ('d',) me mad Exactly right, first parameter is the object itself, second parameter is a 1-tuple of the supplied args. See more explanation below. > > > (and on a side note if i dont include the *args i get an invalid number of > parameters supplied message.) > why is it returning the value in this format ('d',) ? > i cant get x == d > i guess that value 'd' is stored in a tuple and i'd like to get it out of > there. No, 'd' is stored as the value of the attribute you've named "x". One of the main points of the whole OO caper is that objects have attributes -- please see later remarks about the tutorial. > > so basically the function returns nope as it stands > > python is sure different from other languages i have used. > > thanks for any help, > jim > > > class getQryStr: > def __init__(self,op): > print op > self.x = 'd' You probably meant self.x = op > def returnStr(x,*args): Like the first (__init__) method, this should have the mandatory "self" argument, plus *one* other arg .. *if* you need it. It's not apparent why you are calling the constructor *and* the returnStr method *each* with 'd'. > > print '%s %s me mad' % (x,args) > if x == 'd': Here x is the object that you have created. The first argument to a method is the object itself, and is conventionally named "self". It must be declared in the method itself def amethod(self, arg1, arg2): but is supplied automatically when you invoke it anobj.amethod('foo', 42) [snip] Please consider working your way through the Python tutorial http://docs.python.org/tut/node11.html and/or one of the free e-books e.g. http://www.byteofpython.info/ At the end of this post is a modified version of your script which shows what is going on under normal expected usage. HTH, John 8<=== demo script === C:\junk>type use_self.py class getQryStr: def __init__(self, op): print '__init__ ... op:%r' % op self.x = op def returnStr(self, arg): print 'returnStr ... self.x:%r arg:%r' % (self.x, arg) return '=%s=%s=' % (self.x, arg) obj = getQryStr('blah') print '__main__ ... obj.x:%r' % obj.x s = obj.returnStr('yadda') print '__main__ ... s:%r' % s 8<=== output from demo script === C:\junk>use_self.py __init__ ... op:'blah' __main__ ... obj.x:'blah' returnStr ... self.x:'blah' arg:'yadda' __main__ ... s:'=blah=yadda=' 8<=== end === From go at away.com Thu Jun 1 02:34:35 2006 From: go at away.com (3rdshiftcoder) Date: Thu, 01 Jun 2006 00:34:35 GMT Subject: beginner: using parameter in functions References: Message-ID: thanks very much John! so i can have self as function parameter as well as in a method. that allowed me to use properties to retrieve the value set in the constructor. i just changed the function return statement and it worked. i was working along these lines but couldnt get it up and running as fast as you posted. templating sure is a great way to create dynamic query strings. very cool so far but still lots to learn. thanks again, jim "John McMonagle" wrote in message news:mailman.6388.1149119924.27775.python-list at python.org... > On Wed, 2006-05-31 at 23:24 +0000, 3rdshiftcoder wrote: >> hi- >> >> i am having trouble using parameter values in my function and to be >> honest a >> little trouble with >> member variables. i am trying to pass in the argument 'd' representing >> delete. >> what the code will do is if it is 'd' it will make a delete query >> template >> string. >> if it is an 'i' then insert query etc. >> >> this is the results of my attempt to print the contents of the parameter >> values. >> <__main__.getQryStr instance at 0x01151D50> ('d',) me mad >> >> >> (and on a side note if i dont include the *args i get an invalid number >> of >> parameters supplied message.) >> why is it returning the value in this format ('d',) ? >> i cant get x == d >> i guess that value 'd' is stored in a tuple and i'd like to get it out of >> there. >> >> so basically the function returns nope as it stands >> >> python is sure different from other languages i have used. >> >> thanks for any help, >> jim >> > > > Try, the following: > > class getQryStr: > def __init__(self,op): > print op > self.x = 'd' > def returnStr(self, *args): > > print '%s %s me mad' % (self.x,args) > if self.x == 'd': > s = Template("delete from columndef where tblid = $tblid and > colname = $colname") > else: > return 'nope' #this else is just for illustration and > testing > > d = dict(tblid=t.tblid.getText(), colname=t.colName.getText()) > > print s.substitute(d) > > return s > > > Regards, > > John > > > > -- > This message has been scanned for viruses and > dangerous content by MailScanner, and is > believed to be clean. > From rpdooling at gmail.com Thu Jun 1 02:31:40 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 31 May 2006 17:31:40 -0700 Subject: Variable name has a typo, but code still works. Why? References: <1149082236.151844.99600@u72g2000cwu.googlegroups.com> <1149083447.370584.197070@f6g2000cwb.googlegroups.com> <1149116972.201718.155660@h76g2000cwa.googlegroups.com> Message-ID: <1149121900.895494.24360@y43g2000cwc.googlegroups.com> > I can only assume that there was some type of cache problem. Could it > have been in the .pyc? I thought that was recompiled every time a .py > is run/set to be interpreted. If you are on Windows, check your PATHEXT environment variable and make sure that .py is listed ahead of .pyc and any other .py? See, e.g., a bug in earlier versions of ActiveState distrib http://tinyurl.com/qok9v rd "Electricity is actually made up of extremely tiny particles called electrons, that you cannot see with the naked eye unless you have been drinking."--Dave Barry From noway at sorry.com Thu Jun 1 02:50:37 2006 From: noway at sorry.com (Giovanni Bajo) Date: Thu, 01 Jun 2006 00:50:37 GMT Subject: struct: type registration? Message-ID: Hello, given the ongoing work on struct (which I thought was a dead module), I was wondering if it would be possible to add an API to register custom parsing codes for struct. Whenever I use it for non-trivial tasks, I always happen to write small wrapper functions to adjust the values returned by struct. An example API would be the following: ============================================ def mystring_len(): return 20 def mystring_pack(s): if len(s) > 20: raise ValueError, "a mystring can be at max 20 chars" s = (s + "\0"*20)[:20] s = struct.pack("20s", s) return s def mystring_unpack(s): assert len(s) == 20 s = struct.unpack("20s", s)[0] idx = s.find("\0") if idx >= 0: s = s[:idx] return s struct.register("S", mystring_pack, mystring_unpack, mystring_len) # then later foo = struct.unpack("iilS", data) ============================================ This is only an example, any similar API which might fit better struct internals would do as well. As shown, the custom packer/unpacker can call the original pack/unpack as a basis for their work. I guess an issue with this could be the endianess problem: it would make sense if, when called recursively, struct.pack/unpack used by the default the endianess specified by the external format string. -- Giovanni Bajo From george.sakkis at gmail.com Thu Jun 1 03:03:59 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 31 May 2006 18:03:59 -0700 Subject: ideas for programs? References: Message-ID: <1149123839.683480.178380@y43g2000cwc.googlegroups.com> Brandon McGinty wrote: > Hi, > I've been learning python for the past couple of months and writing misc > scripts here and there, along with some web apps. > I'm wondering if anyone has ideas of programs I might try my hand at making? > I'd appreciate it if they don't use images, because I'm blind. One ambitious idea would be to implement (a subset of) MDX, the Multi-Dimensional eXpressions language (http://msdn2.microsoft.com/en-us/library/ms145506.aspx). If you have any java experience, there is an open source implementation in it so you don't have to start from scratch: http://mondrian.sourceforge.net. George From DustanGroups at gmail.com Thu Jun 1 03:12:51 2006 From: DustanGroups at gmail.com (Dustan) Date: 31 May 2006 18:12:51 -0700 Subject: Downloading and Displaying an Image from the Internet in Tkinter Message-ID: <1149124371.337732.3650@f6g2000cwb.googlegroups.com> The title pretty much says it all. What is the easiest way in Tkinter to display an image from the internet given the URL? From bnblazer at gmail.com Thu Jun 1 03:48:30 2006 From: bnblazer at gmail.com (Brian) Date: 31 May 2006 18:48:30 -0700 Subject: TSV to HTML In-Reply-To: <447e268a$0$3699$4d3efbfe@news.sover.net> References: <1149098823.979329.9220@f6g2000cwb.googlegroups.com> <447e268a$0$3699$4d3efbfe@news.sover.net> Message-ID: <1149126509.984331.306530@h76g2000cwa.googlegroups.com> First let me say that I appreciate the responses that everyone has given. A friend of mine is a ruby programmer but knows nothing about python. He gave me the script below and it does exactly what I want, only it is in Ruby. Not knowing ruby this is greek to me, and I would like to re-write it in python. I ask then, is this essentially what others here have shown me to do, or is it in a different vein all together? Code: class TsvToHTML @@styleBlock = <<-ENDMARK ENDMARK def TsvToHTML::wrapTag(data,tag,modifier = "") return "<#{tag} #{modifier}>" + data + "\n" end # wrapTag def TsvToHTML::makePage(source) page = "" rowNum = 0 source.readlines.each { |record| row = "" record.chomp.split("\t").each { |field| # replace blank fields with   field.sub!(/^$/," ") # wrap in TD tag, specify style row += wrapTag(field,"td","class=\"" + ((rowNum == 0)?"cellTitle":"cell#{rowNum % 2}") + "\"") } rowNum += 1 # wrap in TR tag, add row to page page += wrapTag(row,"tr") + "\n" } # finish page formatting [ [ "table","cellpadding=0 cellspacing=0 border=0" ], "body","html" ].each { |tag| page = wrapTag(@@styleBlock,"head") + page if tag == "html" page = wrapTag(page,*tag) } return page end # makePage end # class # stdin -> convert -> stdout print TsvToHTML.makePage(STDIN) From yinglcs at gmail.com Thu Jun 1 03:52:41 2006 From: yinglcs at gmail.com (yinglcs at gmail.com) Date: 31 May 2006 18:52:41 -0700 Subject: Save data to a file thru a http connection In-Reply-To: <447e0221$1@nntp0.pdx.net> References: <1149100667.391141.222280@i40g2000cwc.googlegroups.com> <447e0221$1@nntp0.pdx.net> Message-ID: <1149126761.726836.73360@y43g2000cwc.googlegroups.com> Scott, Can you please tell me which chapter of the tutorial that you are referring to http://docs.python.org/tut/tut.html? The only chapter that I find about http is chapter 10.7, but it does not have the example that you are referring to Scott David Daniels wrote: > yinglcs at gmail.com wrote: > > I am new to python. I read an example here about how to fetch data thru > > a HTTP connection: > > http://diveintopython.org/http_web_services/review.html, > > > > My question is how can i save the data to a file after reading it from > > a http connection. > > Do the tutorial and this and many other things will become clear. > > Instead of just "print sometext", do something like: > ... > f = open('filename', 'w') > ... > print >>f, sometext > ... (possibly more prints like the above). > f.close() > > --Scott David Daniels > scott.daniels at acm.org From sjmachin at lexicon.net Thu Jun 1 04:06:15 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 01 Jun 2006 12:06:15 +1000 Subject: struct: type registration? In-Reply-To: References: Message-ID: <447e4b98$1@news.eftel.com> On 1/06/2006 10:50 AM, Giovanni Bajo wrote: > Hello, > > given the ongoing work on struct (which I thought was a dead module), I was > wondering if it would be possible to add an API to register custom parsing > codes for struct. Whenever I use it for non-trivial tasks, I always happen to > write small wrapper functions to adjust the values returned by struct. > > An example API would be the following: > > ============================================ > def mystring_len(): > return 20 > > def mystring_pack(s): > if len(s) > 20: > raise ValueError, "a mystring can be at max 20 chars" > s = (s + "\0"*20)[:20] Have you considered s.ljust(20, "\0") ? > s = struct.pack("20s", s) > return s I am an idiot, so please be gentle with me: I don't understand why you are using struct.pack at all: |>>> import struct |>>> x = ("abcde" + "\0" * 20)[:20] |>>> x 'abcde\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' |>>> len(x) 20 |>>> y = struct.pack("20s", x) |>>> y == x True |>>> Looks like a big fat no-op to me; you've done all the heavy lifting yourself. > > def mystring_unpack(s): > assert len(s) == 20 > s = struct.unpack("20s", s)[0] Errrm, g'day, it's that pesky idiot again: |>>> z = struct.unpack("20s", y)[0] |>>> z 'abcde\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' |>>> z == y == x True > idx = s.find("\0") > if idx >= 0: > s = s[:idx] > return s Have you considered this: |>>> z.rstrip("\0") 'abcde' |>>> ("\0" * 20).rstrip("\0") '' |>>> ("x" * 20).rstrip("\0") 'xxxxxxxxxxxxxxxxxxxx' > > struct.register("S", mystring_pack, mystring_unpack, mystring_len) > > # then later > foo = struct.unpack("iilS", data) > ============================================ > > This is only an example, any similar API which might fit better struct > internals would do as well. > > As shown, the custom packer/unpacker can call the original pack/unpack as a > basis for their work. I guess an issue with this could be the endianess > problem: it would make sense if, when called recursively, struct.pack/unpack > used by the default the endianess specified by the external format string. From sjmachin at lexicon.net Thu Jun 1 04:14:45 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 01 Jun 2006 12:14:45 +1000 Subject: Save data to a file thru a http connection In-Reply-To: <1149126761.726836.73360@y43g2000cwc.googlegroups.com> References: <1149100667.391141.222280@i40g2000cwc.googlegroups.com> <447e0221$1@nntp0.pdx.net> <1149126761.726836.73360@y43g2000cwc.googlegroups.com> Message-ID: <447E4D95.4040805@lexicon.net> On 1/06/2006 11:52 AM, yinglcs at gmail.com wrote: > Scott, > > Can you please tell me which chapter of the tutorial that you are > referring to http://docs.python.org/tut/tut.html? > > The only chapter that I find about http is chapter 10.7, but it does > not have the example that you are referring to Break the problem up into two parts: (1) Get some data. You've achieved that, using HTTP. (2) Save some data to a file. Doesn't matter *how* you got the data. You need to know how to open a file for writing and how to write to it and how to close it when you've finished. Look for the section in the tutorial about *files*. Better still, read *all* the sections in the tutorial :-) > > Scott David Daniels wrote: >> yinglcs at gmail.com wrote: >>> I am new to python. I read an example here about how to fetch data thru >>> a HTTP connection: >>> http://diveintopython.org/http_web_services/review.html, >>> >>> My question is how can i save the data to a file after reading it from >>> a http connection. >> Do the tutorial and this and many other things will become clear. >> >> Instead of just "print sometext", do something like: >> ... >> f = open('filename', 'w') >> ... >> print >>f, sometext >> ... (possibly more prints like the above). >> f.close() >> >> --Scott David Daniels >> scott.daniels at acm.org > From go at away.com Thu Jun 1 04:21:57 2006 From: go at away.com (3rdshiftcoder) Date: Thu, 01 Jun 2006 02:21:57 GMT Subject: beginner: using parameter in functions References: <447e32f3@news.eftel.com> Message-ID: <9bsfg.240$Cw3.174@trndny01> "John Machin" wrote in message news:447e32f3 at news.eftel.com... thanks for the help. it is really appreciated. i am going to do some more reading in the next couple of days. jim From nkammah at yahoo.fr Thu Jun 1 05:08:30 2006 From: nkammah at yahoo.fr (kepioo) Date: 31 May 2006 20:08:30 -0700 Subject: How to access the content of notepad with Python? Message-ID: <1149131310.763870.29250@j55g2000cwa.googlegroups.com> Hi, I have a software running on my computer that really looks like notepad ( same interface, different name). I need to write a script that will capture the content of this software --> the text written inside. Is it possible using win32 libs? any clue? Thanks! From rupole at hotmail.com Thu Jun 1 05:35:50 2006 From: rupole at hotmail.com (Roger Upole) Date: Wed, 31 May 2006 23:35:50 -0400 Subject: Try/Except for ADSI GetObject References: Message-ID: <1149132664_5885@sp6iad.superfeed.net> "LittlePython" wrote in message news:al5fg.9877$ho6.1459 at trnddc07... >I am a little confused on why I can not detect an object that does not exist > with a try and except. If I understand ADSI correctly from what I have read > you do not create these objects but rather get them. They already exist. I > believe if I do the equivalent in VB I would generate an error when I try to > get an object that does not exist (can not find). I don't get an error when doing a GetObject in VBS for a nonexistent domain. What have I done wrong? > I have included the function below that works in ever respect but detecting > incorrect NT Domain Names (objects that do not exist) . Any tips, insight or > comments would be welcome by this newbie. You should be able to use win32net.NetValidateName to verify that the domain exists before doing any more operations. hth Roger ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- From rupole at hotmail.com Thu Jun 1 05:37:55 2006 From: rupole at hotmail.com (Roger Upole) Date: Wed, 31 May 2006 23:37:55 -0400 Subject: WinPops References: Message-ID: <1149132789_5889@sp6iad.superfeed.net> "Hari Sekhon" wrote in message news:mailman.6230.1148640634.27775.python-list at python.org... > Hi, > Is there a way of sending winpops (Windows Pop-Up / Net Send messages) in python? > > Perhaps some library or something that I can use under both Windows and Linux? > > Hari On Windows, you can use win32net.NetMessageBufferSend. Roger ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- From Bulkan at gmail.com Thu Jun 1 05:47:32 2006 From: Bulkan at gmail.com (placid) Date: 31 May 2006 20:47:32 -0700 Subject: How to access the content of notepad with Python? In-Reply-To: <1149131310.763870.29250@j55g2000cwa.googlegroups.com> References: <1149131310.763870.29250@j55g2000cwa.googlegroups.com> Message-ID: <1149133652.024007.220150@i39g2000cwa.googlegroups.com> kepioo wrote: > Hi, > > I have a software running on my computer that really looks like notepad > ( same interface, different name). I need to write a script that will > capture the content of this software --> the text written inside. > Dont know about win32, but if you want an easy solution then save the text you want to capture and then read it via Python! From Bulkan at gmail.com Thu Jun 1 05:52:49 2006 From: Bulkan at gmail.com (placid) Date: 31 May 2006 20:52:49 -0700 Subject: Is device Connected Windows? Message-ID: <1149133969.191368.224660@h76g2000cwa.googlegroups.com> Hi all, Just wondering is there a way (not brute force) to check if a usb storage device is connected? The brute force method im talking about is doing a os.path.isdir() or os.path.isdir() on all the drive letters from A-Z, because you know that this usb device contains a folder called A or file called foo.txt. Thanks in Advance From timr at probo.com Thu Jun 1 06:42:22 2006 From: timr at probo.com (Tim Roberts) Date: Thu, 01 Jun 2006 04:42:22 GMT Subject: TIming References: Message-ID: WIdgeteye wrote: >On Tue, 30 May 2006 16:15:44 +1000, John McMonagle wrote: > >> Tim Roberts is right. As you are on linux, I suggest you investigate the >> at command - very user friendly and not at all complicated. > >I have been using Slackware for over 10 years I know all about the >commands on the OS. > >If you guys don't have an answer to the question just say so. But don't >give me suggestions on how to use an OS I have been using most likely >longer than 90% of the people using linux today. > >This is the comp.lang.python news group not the linux news group. If I >didn't want to write the Python code and I wanted to use the OS commands >instead I would. Utter nonsense. If someone posted on comp.lang.python that they wanted to know how to write a DMA-based PCI driver in Python, I am sure as heck going to tell them that there are better tools for the job and better newsgroups for the question. >Python is cross platform. Linux is not. I intend to release the software >to the general public someday when it is done. I want it cross platform. Windows also has an "at" command. However, you are not going to be able to write a television-based application that is cross platform. The video tools are just too different. >BTW in the time it took me NOT to get an answer for my question in this so >called Python NG, I figured it out for myself. That's almost always the case with newsgroups. They are NOT a real-time medium. >This PYTHON NG blows to high heaven. Whats worse, the answers I got were >most likely from people who know SQUAT about Python scripting. That's why >they gave me such lame fucking answers. We did not give you "lame fucking answers". We gave you solutions to the problem you posed. If the problem statement wasn't clear enough, that isn't our fault. >Idiots. It takes one to know one. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From jstroud at ucla.edu Thu Jun 1 06:51:25 2006 From: jstroud at ucla.edu (James Stroud) Date: Wed, 31 May 2006 21:51:25 -0700 Subject: ideas for programs? In-Reply-To: References: Message-ID: A digest of the major points summarizing the consensus opinion: Thomas Bartkus wrote: > Python is your tool to put your expertise on a computer. Skill with Python, > or any computer language for that matter, counts for little. And akameswaran at gmail.com wrote: > As far as employment. I come from a java background, and that seems > the only language I can pay the bills with:). Particularly in the US > paid python jobs are hard to come by. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From webraviteja at gmail.com Thu Jun 1 07:00:08 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 31 May 2006 22:00:08 -0700 Subject: How to access the content of notepad with Python? In-Reply-To: <1149131310.763870.29250@j55g2000cwa.googlegroups.com> References: <1149131310.763870.29250@j55g2000cwa.googlegroups.com> Message-ID: <1149138007.952375.22560@u72g2000cwu.googlegroups.com> > I have a software running on my computer that really looks like notepad > ( same interface, different name). I need to write a script that will > capture the content of this software --> the text written inside. > > Is it possible using win32 libs? any clue? http://www.openqa.org/pywinauto/ The example on their home page is in fact how to automate Notepad. I am sure you can work from there. From paddy3118 at netscape.net Thu Jun 1 07:31:15 2006 From: paddy3118 at netscape.net (Paddy) Date: 31 May 2006 22:31:15 -0700 Subject: TSV to HTML References: <1149098823.979329.9220@f6g2000cwb.googlegroups.com> <447e268a$0$3699$4d3efbfe@news.sover.net> <1149126509.984331.306530@h76g2000cwa.googlegroups.com> Message-ID: <1149139875.503669.57900@h76g2000cwa.googlegroups.com> Brian wrote: > First let me say that I appreciate the responses that everyone has > given. > > A friend of mine is a ruby programmer but knows nothing about python. > He gave me the script below and it does exactly what I want, only it is > in Ruby. Not knowing ruby this is greek to me, and I would like to > re-write it in python. > > I ask then, is this essentially what others here have shown me to do, > or is it in a different vein all together? > Leif's Python example uses the csv module which understands a lot more about the peculiarities of the CSV/TSV formats. The Ruby example prepends a block. The Ruby example splits each line to form a table row and each row on tabs, to form the cells. The thing about TSV/CSV formats is that their is no one format. you need to check how your TSV creator generates the TSV file: Does it put quotes around text fields? What kind of quotes? How does it represent null fields? Might you get fields that include newlines? - P.S. I'm not a Ruby programmer, just read the source ;-) From anatoli.barski at googlemail.com Thu Jun 1 09:04:26 2006 From: anatoli.barski at googlemail.com (anatoli.barski at googlemail.com) Date: 1 Jun 2006 00:04:26 -0700 Subject: how to print newline in xml? In-Reply-To: References: <1149023930.292203.152540@u72g2000cwu.googlegroups.com> Message-ID: <1149145466.190011.146250@i39g2000cwa.googlegroups.com> Thank you for a possible solution, but it's not what I'm looking for, cause something like would look quite similar... for big elements like robot it would be ok to use comment as a child of element - but imagine I'd like to comment transformation: I wouldn't like to make this element parent of a description - it is not nice - I have lots of such elements. It is important that a user after having a glance at the document is able to quickly find and change some values. I don't want to bother him with reading documentation nodes - but if he needs - they should be there... the only possible solution I can think of would be: > How about: > > > armar3 > : > : > > > XML editor + xpath makes this way more easier to use by humans compared to > normal comments. Also, if you declare several of comment elements > (summary, description, author, etc.) you can auto generate documentation > etc. > > -- > John MexIT: http://johnbokma.com/mexit/ > personal page: http://johnbokma.com/ > Experienced programmer available: http://castleamber.com/ > Happy Customers: http://castleamber.com/testimonials.html From laura at voipro.nl Thu Jun 1 09:08:32 2006 From: laura at voipro.nl (Laura van Tuin) Date: Thu, 1 Jun 2006 09:08:32 +0200 Subject: Python Programmerwanted Message-ID: Python programmer wanted Our fast-growing team of software developers is currently looking for a (junior) Python programmer to assist in the development of our core technology. To extend the core team we're looking for a talented individual with specifically: thorough knowledge of Linux and Python experience with Zope and Plone is recommended knowledge of VoIP including open standards such as SIP at least HBO/academic education fluent in English, preferably also in Dutch Working at Voipro is about team work and sharing in the success of the company. Our compensation is highly competitive and our organization has room for entrepreneurial professionals with experience in the telecommunication and technology markets. Professionalism, relationship management, and creativity are our core values and inherent strengths in our team. Voipro extends its founders tradition of delivering technological solutions in the technology and telecommunication markets successfully. Our fast growing team is motivated to deliver success to its investors, customers, and partners. If you are interested please contact Voipro Nederland BV - Laura van Tuin +31 20 7884000 / laura at voipro.nl -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/python-list/attachments/20060601/a31f9ee4/attachment.htm From kapil.sundrani at wipro.com Thu Jun 1 09:08:25 2006 From: kapil.sundrani at wipro.com (kapil.sundrani at wipro.com) Date: Thu, 1 Jun 2006 12:38:25 +0530 Subject: problem with file upload... Message-ID: <865660148009AD47BBBFD82BFED3A92601E785A1@BLR-EC-MBX04.wipro.com> I have a problem in uploading a file. The input tag looks like and the form tag looks like.
But still after form submission I don't get the file data. Debugging shows that the input field is being taken as a MinifieldStorage instead of FieldStorage. Thanks in advance for any help :-) Regards, Kapil The information contained in this electronic message and any attachments to this message are intended for the exclusive use of the addressee(s) and may contain proprietary, confidential or privileged information. If you are not the intended recipient, you should not disseminate, distribute or copy this e-mail. Please notify the sender immediately and destroy all copies of this message and any attachments. WARNING: Computer viruses can be transmitted via email. The recipient should check this email and any attachments for the presence of viruses. The company accepts no liability for any damage caused by any virus transmitted by this email. www.wipro.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/python-list/attachments/20060601/1b8bad49/attachment.html From grflanagan at yahoo.co.uk Thu Jun 1 09:32:44 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 1 Jun 2006 00:32:44 -0700 Subject: shuffling elements of a list References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> Message-ID: <1149147164.012044.66960@u72g2000cwu.googlegroups.com> Ben Finney wrote: [snip] > > Please don't write C in Python. The 'for' statement allows iteration > directly over a sequence, no need to maintain an index. Also, the > modulus operator is called for with your cycling of the pile index. > > pile_index = 0 > for card in deck: > piles[pile_index].append(card) > pile_index = (pile_index + 1) % numpiles > no need to maintain an index ;-) piles = [ list() for _ in range(n) ] for i, card in enumerate(deck): piles[i % numpiles].append(card) Gerard From pemboa at gmail.com Thu Jun 1 09:36:06 2006 From: pemboa at gmail.com (Arthur Pemberton) Date: Thu, 1 Jun 2006 02:36:06 -0500 Subject: Best way to do data source abstraction Message-ID: <16de708d0606010036j65d64096m5a4dcb0c04c5656a@mail.gmail.com> What is the best way to do data source abtraction? For example have different classes with the same interface, but different implementations. I was thinking of almost having classA as my main class, and have classA dynamically "absorb" classFood into to based on the extension of the input file received by classA. But this doesn't seem possible. Please advise. Thank you. -- To be updated... From bignose+hates-spam at benfinney.id.au Thu Jun 1 09:52:00 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 01 Jun 2006 17:52:00 +1000 Subject: shuffling elements of a list References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> <1149147164.012044.66960@u72g2000cwu.googlegroups.com> Message-ID: <87bqtdz527.fsf@benfinney.id.au> "Gerard Flanagan" writes: > Ben Finney wrote: > > pile_index = 0 > > for card in deck: > > piles[pile_index].append(card) > > pile_index = (pile_index + 1) % numpiles > > > > no need to maintain an index ;-) > > piles = [ list() for _ in range(n) ] > for i, card in enumerate(deck): > piles[i % numpiles].append(card) That's a matter of style. I prefer what I wrote, since I've given an explicit name to the calculation you're doing inside the [] operator; that way, anyone reading the code knows *why* the calculation is done in this particular case. If, of course, the index was a simple increment-by-one each time, your 'enumerate' usage would be clearer. -- \ "We spend the first twelve months of our children's lives | `\ teaching them to walk and talk and the next twelve years | _o__) telling them to sit down and shut up." -- Phyllis Diller | Ben Finney From __peter__ at web.de Thu Jun 1 09:52:25 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Jun 2006 09:52:25 +0200 Subject: shuffling elements of a list References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> <1149147164.012044.66960@u72g2000cwu.googlegroups.com> Message-ID: Gerard Flanagan wrote: > Ben Finney wrote: >> pile_index = 0 >> for card in deck: >> piles[pile_index].append(card) >> pile_index = (pile_index + 1) % numpiles >> > > no need to maintain an index ;-) > > piles = [ list() for _ in range(n) ] > for i, card in enumerate(deck): > piles[i % numpiles].append(card) No need to maintain an index ;-) piles = [deck[start::numpiles] for start in range(numpiles)] Assuming deck is a list, that is. Peter From nicogrubert at gmail.com Thu Jun 1 10:00:49 2006 From: nicogrubert at gmail.com (Nico Grubert) Date: Thu, 01 Jun 2006 10:00:49 +0200 Subject: os.popen3() - how to close cmd window automatically? In-Reply-To: References: Message-ID: <447E9EB1.6090506@gmail.com> > replace console=[... by windows=[... in your setup.py Works perfect. Thank you, Rony! From michele.petrazzo at TOGLIunipex.it Thu Jun 1 10:04:28 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Thu, 01 Jun 2006 08:04:28 GMT Subject: ctypes pointers and SendMessage In-Reply-To: <1149116010.351538.258990@g10g2000cwb.googlegroups.com> References: <1149116010.351538.258990@g10g2000cwb.googlegroups.com> Message-ID: Metalone wrote: > I would like to call > windll.user32.SendMessageA(hwnd, win32con.WM_COMMAND, wParam, lParam) > where > lParam represents a pointer to an object. and the others? > > And also convert this pointer back to an object reference inside of > wnd_proc > def wnd_proc(hwnd, msg, wParam, lParam): > > So something like this: > class X(Structure): > def __init__(self, x): > self.v = x > > What am I doing wrong? > I don't know if you want to create a "real" C structure. If yes this is the wrong method: >>> class X(Structure): ... _fields_ = [("x", c_int), ] ... >>> x1 = X(1) >>> x1.x 1 >>> http://starship.python.net/crew/theller/ctypes/tutorial.html -> Structures and Unions Michele From sybrenUSE at YOURthirdtower.com.imagination Thu Jun 1 10:02:34 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Thu, 1 Jun 2006 10:02:34 +0200 Subject: Best way to do data source abstraction References: Message-ID: Arthur Pemberton enlightened us with: > What is the best way to do data source abtraction? That depends on your data source. For files, file-like objects are an abstraction. For databases there is PEP 249. > I was thinking of almost having classA as my main class, and have > classA dynamically "absorb" classFood into to based on the extension > of the input file received by classA. But this doesn't seem > possible. You don't explain the most important part - "absorb". What does that mean? And what does it mean to have classA "almost" as your main class? Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From andyrsmith at googlemail.com Thu Jun 1 10:14:28 2006 From: andyrsmith at googlemail.com (andyrsmith at googlemail.com) Date: 1 Jun 2006 01:14:28 -0700 Subject: Best Python Editor References: Message-ID: <1149149668.113003.142940@j55g2000cwa.googlegroups.com> If we could go back to emacs again for a second... I'm still using emacs but have been playing with a few other ide's (wing, komodo + pydev) are the ones i've given a go recently. However I still end up coming back to emacs for what I consider to be emacs mode's piece of 'killer functionality', (well, killer for me anyway :-) ) which is the C-c C-c shortcut to send the contents of the current buffer to a running interpreter. (i.e. one long-running interpreter that behaves as if the entire buffer had been retyped). Not very useful on first glance, but compared with what I've found to be the 'standard' run-this-script-in-a-new-interpreter function the other ides seem to have it has the following advantages. 1/ No wait for another interpreter to start up 2/ It lets you do the following in a script which lends itself to a much tighter edit-run loop ... try: runOnce except: doSomePainfulDataGathering() runOnce = 1 doSomeLessPainfulDataProcessing() i.e. the painful part will only get executed once, so its cost can be amortized over multiple runs of the script. Of course care has to be taken to ensure the script doesn't violate causality (i.e. code can creep in that depends on variables that haven't yet been initialized) , but in practice I haven't found it to be much of a problem. (And can be checked quickly by simply killing the running interpreter and starting a fresh one). Anyway, the question is whether or not any of the other IDE's support this style of working, (I say I'd *played* with some of them but can't swear I'd dug through every nook and cranny of all of their menu options) Cheers, A. From yairchu at gmail.com Thu Jun 1 10:16:14 2006 From: yairchu at gmail.com (yairchu at gmail.com) Date: 1 Jun 2006 01:16:14 -0700 Subject: Best Python Editor References: Message-ID: <1149149773.999940.13500@i40g2000cwc.googlegroups.com> > Can anyone tell me a good python editor/IDE? > It would be great if you can provide the download link also. WingIDE is very good. It gives very nice completions and has a nice thing called "source assistant" that shows the help of the function you're standing on and etc. But I don't think it's open-source and freei if that bothers you http://www.wingware.com/ Another good one is idlespoon. this one is open-source and freei http://idlespoon.python-hosting.com/ From tim.golden at viacom-outdoor.co.uk Thu Jun 1 10:23:06 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 1 Jun 2006 09:23:06 +0100 Subject: Is device Connected Windows? Message-ID: [placid] | Just wondering is there a way (not brute force) to check if a usb | storage device is connected? Hmmm. How do you identify "a usb storage device" to know that it is or isn't connected? You can certainly do something useful with wmi. eg, import wmi c = wmi.WMI () for usb_disk in c.Win32_DiskDrive (InterfaceType="USB"): print usb_disk.Caption print usb_disk.PNPDeviceID Now, assuming that the PNPDeviceID is unique enough for your purpose, you could probably do something with it to keep hold of it and then check later whether the same device is still inserted. One possibility is to use a WMI watcher to spot when devices are removed: import wmi c = wmi.WMI () usb_watcher = c.watch_for ( notification_type="Deletion", wmi_class="Win32_DiskDrive", delay_secs=2, InterfaceType="USB" ) while True: usb_removed = usb_watcher () # can optionally timeout print usb_removed.PNPDeviceID Lots of other possibilities, a polling loop, two watchers, one for creation one for deletion etc. Depends exactly what your requirements are. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From ray_usenet at yahoo.com Thu Jun 1 10:28:37 2006 From: ray_usenet at yahoo.com (Ray) Date: 1 Jun 2006 01:28:37 -0700 Subject: How do you practice Python? Message-ID: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> In our field, we don't always get to program in the language we'd like to program. So... how do you practice Python in this case? Say you're doing J2EE right now. How do you practice Python to keep your skills sharp? I liked Python Challenge, but there were too many PIL there, something that I doubt I'll ever use, so there must be a better way. Thanks Ray From ray_usenet at yahoo.com Thu Jun 1 10:38:17 2006 From: ray_usenet at yahoo.com (Ray) Date: 1 Jun 2006 01:38:17 -0700 Subject: How do you practice programming? Message-ID: <1149151097.741307.79440@f6g2000cwb.googlegroups.com> OK, maybe I shoot a more general question to the group since there are so many great programmers here: how do you practice your craft? I do it in the following way: 1. Set aside 30 minutes to 1 hour a day to read up on the latest development, be it about the tool I'm using, the language, or the platform, or the framework, etc. 2. Once every 1-2 months, go to Amazon, and look for the book with the best reviews in a particular technology (e.g.: SQL Cookbook, etc.) 3. Practice something that I may not be using currently at work, but always good to know, e.g.: I try to be reasonably competent in at least 2 major current languages--right now it's Java and C#, and 1 dynamic language, which has been Python for quite some time. SQL is always useful, so I try to practice that, especially the more complex queries involving group bys and window function, etc. How do you do your practice? From anthra.norell at tiscalinet.ch Thu Jun 1 10:51:57 2006 From: anthra.norell at tiscalinet.ch (Anthra Norell) Date: Thu, 1 Jun 2006 10:51:57 +0200 Subject: losing handles of open files Message-ID: <000c01c68558$a48a9680$0201a8c0@mcuf7> Hi If a piece of code exits with an exception before it closes an open file, that file seems to remain locked, which is real pain in the butt if I develop a file in parallel with a piece of code. Is there a way to close such lost files short of starting a new session? Frederic -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/python-list/attachments/20060601/dfdf4eef/attachment.htm From onurb at xiludom.gro Thu Jun 1 10:50:53 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 01 Jun 2006 10:50:53 +0200 Subject: How do you practice Python? In-Reply-To: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> References: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> Message-ID: <447eaae0$0$20867$636a55ce@news.free.fr> Ray wrote: > In our field, we don't always get to program in the language we'd like > to program. So... how do you practice Python in this case? Say you're > doing J2EE right now. Hopefully not ! > How do you practice Python to keep your skills > sharp? How *would* I do ? Well, perhaps I'd use Jython ? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From ray_usenet at yahoo.com Thu Jun 1 10:56:54 2006 From: ray_usenet at yahoo.com (Ray) Date: 1 Jun 2006 01:56:54 -0700 Subject: How do you practice Python? In-Reply-To: <447eaae0$0$20867$636a55ce@news.free.fr> References: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> <447eaae0$0$20867$636a55ce@news.free.fr> Message-ID: <1149152214.215907.31800@i39g2000cwa.googlegroups.com> bruno at modulix wrote: > > In our field, we don't always get to program in the language we'd like > > to program. So... how do you practice Python in this case? Say you're > > doing J2EE right now. > > Hopefully not ! I am :-( > > How do you practice Python to keep your skills > > sharp? > > How *would* I do ? Well, perhaps I'd use Jython ? Um, I mean, what if you have to use something other than Python/Jython/IronPython? :) How do you keep your Python skill sharp? > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in 'onurb at xiludom.gro'.split('@')])" From onurb at xiludom.gro Thu Jun 1 10:55:23 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 01 Jun 2006 10:55:23 +0200 Subject: How do you practice programming? In-Reply-To: <1149151097.741307.79440@f6g2000cwb.googlegroups.com> References: <1149151097.741307.79440@f6g2000cwb.googlegroups.com> Message-ID: <447eabee$0$19567$636a55ce@news.free.fr> Ray wrote: > OK, maybe I shoot a more general question to the group since there are > so many great programmers here: how do you practice your craft? I'm certainly not one of them, but... (snip) > How do you do your practice? > 1/ programming 2/ programming 3/ lurking here, reading posts and sometimes trying to answer, reading source code of the oss apps/frameworks I'm working with, searching practical solutions in the cookbook etc 4/ programming -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From ray_usenet at yahoo.com Thu Jun 1 11:00:28 2006 From: ray_usenet at yahoo.com (Ray) Date: 1 Jun 2006 02:00:28 -0700 Subject: How do you practice programming? In-Reply-To: <447eabee$0$19567$636a55ce@news.free.fr> References: <1149151097.741307.79440@f6g2000cwb.googlegroups.com> <447eabee$0$19567$636a55ce@news.free.fr> Message-ID: <1149152428.348192.106970@h76g2000cwa.googlegroups.com> bruno at modulix wrote: > 1/ programming > 2/ programming > 3/ lurking here, reading posts and sometimes trying to answer, reading > source code of the oss apps/frameworks I'm working with, searching > practical solutions in the cookbook etc > 4/ programming Yeah, but that's what most of us are doing too, we are programmers after all. But you know, it's like a boxer cannot get better just by going into a lot of fights, he needs good instruction from a good coach. So what would you do? (I guess it's your number #3 above). > > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in 'onurb at xiludom.gro'.split('@')])" From onurb at xiludom.gro Thu Jun 1 11:20:22 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 01 Jun 2006 11:20:22 +0200 Subject: Best way to do data source abstraction In-Reply-To: References: Message-ID: <447eb1ca$0$27292$626a54ce@news.free.fr> Arthur Pemberton wrote: > What is the best way to do data source abtraction? For example have > different classes with the same interface, but different > implementations. > > I was thinking of almost having classA as my main class, and have > classA dynamically "absorb" classFood into to based on the extension > of the input file received by classA. But this doesn't seem possible. Could you explain more accurately what you're trying to do ? FWIW, it seems that a plain old factory function would do ? class DatasourceAbstraction(object): """ base class, factoring common stuff """ # implementation here class JpegFile(DatasourceAbstraction): # .... class PdfFile(DatasourceAbstraction): # .... class TxtFile(DatasourceAbstraction): # .... # etc _classes = { 'jpg' : JpegFile, 'txt' : TxtFile, 'pdf' : PdfFile, # etc.. } def Datasource(inputfile): ext = os.path.splitext(inputfile) return _classes.get(ext, )(inputfile) The fact that there's no 'new' keyword in Python, and that classes are callable objects acting as factories means that it's a no-brainer to use a plain function (eventually disguised as a Class - the client code just doesn't care !-) as factory... Now if I missed the point, please give more explanations... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From petr at tpc.cz Thu Jun 1 12:05:21 2006 From: petr at tpc.cz (Petr Jakes) Date: 1 Jun 2006 03:05:21 -0700 Subject: what is the reasonable (best?) Exception handling strategy? Message-ID: <1149156321.440828.95150@g10g2000cwb.googlegroups.com> I am a little bit confused by all possibilities for exceptions handling in Python (probably because I am not skilled enough??) I did try to search trough this list and reading Python tutorial about Errors and Exceptions but didn't find some "general" answer about exception handling policy (strategy). In the following example each row can IMHO raise an exception (if the Firebird service is not running for example, if the database is corrupted etc.). Do I have to write "try/except" clause on each row? Or to write try/except block (function) where to handle (on one place) all exceptions expected in the program code is a good idea? Or do I have to write own "exception hook"? What about unexpected exceptions? :( def databasExample(h,d,u,p): import kinterbasdb; kinterbasdb.init(type_conv=200) con = kinterbasdb.connect(host=h, database=d,user=u, password=p) cur = con.cursor() insertStatement = cur.prep("some SQL statement......") cur.executemany(insertStatement, ListOfValues) con.commit() cur.close() Generally I am trying to find some general advices or suggestions about exception handling more than the specific answers to the above mentioned code example. Regards Petr Jakes From ullrich at math.okstate.edu Thu Jun 1 12:16:33 2006 From: ullrich at math.okstate.edu (David C. Ullrich) Date: Thu, 01 Jun 2006 05:16:33 -0500 Subject: shuffling elements of a list References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> <1149051212.139046.155340@c74g2000cwc.googlegroups.com> <1149105576.321676.131600@j55g2000cwa.googlegroups.com> Message-ID: <69ft72516amvri3up8fop5rf543s6en1lg@4ax.com> On Wed, 31 May 2006 23:05:14 +0200, Fredrik Lundh wrote: >Roger Miller wrote: > >> DSU seems like a lot of trouble to go through in order to use an O(n >> log n) sorting algorithm to do what can be done in O(N) with a few >> lines of code. The core code of random.shuffle() shows how easy it is >> to do it right: >> >> for i in reversed(xrange(1, len(x))): >> # pick an element in x[:i+1] with which to exchange x[i] >> j = int(random() * (i+1)) >> x[i], x[j] = x[j], x[i] > >easy to do it right? you know, the main reason for adding shuffle to >the standard library was that its way too easy to get it wrong. Heh. And I thought it was just me. _I_ find it easy to get the "limits" wrong, even though I have the idea of the algorithm perfectly straight. Better yet is the number of times I've seen a simply wrong algorithm posted online: >see e.g. this thread: http://tinyurl.com/ppgzq Good example, because we know that EMF is not dumb. I've seen the same algorithm many times - the best example is http://www.cigital.com/papers/download/developer_gambling.php Some poker site posted the simply-wrong algorithm in an effort to convince people that their decks were properly shuffled! ************************ David C. Ullrich From bucodi at yahoo.fr.invalid Thu Jun 1 12:19:30 2006 From: bucodi at yahoo.fr.invalid (Rony Steelandt) Date: Thu, 01 Jun 2006 12:19:30 +0200 Subject: Best Python Editor References: Message-ID: I have to admit that I'm testing eclipse with pydev at the moment, and it looks realy good Rony > Hi, > > Can anyone tell me a good python editor/IDE? > It would be great if you can provide the download link also. > > Thank You, > -Manoj- > > > "SASKEN RATED Among THE Top 3 BEST COMPANIES TO WORK FOR IN INDIA - SURVEY > 2005 conducted by the BUSINESS TODAY - Mercer - TNS India" > > SASKEN BUSINESS DISCLAIMER > This message may contain confidential, proprietary or legally Privileged > information. In case you are not the original intended Recipient of the > message, you must not, directly or indirectly, use, Disclose, distribute, > print, or copy any part of this message and you are requested to delete it > and inform the sender. Any views expressed in this message are those of the > individual sender unless otherwise stated. Nothing contained in this message > shall be construed as an offer or acceptance of any offer by Sasken > Communication Technologies Limited ("Sasken") unless sent with that express > intent and with due authority of Sasken. Sasken has taken enough precautions > to prevent the spread of viruses. However the company accepts no liability > for any damage caused by any virus transmitted by this email -- --- Rony Steelandt BuCodi rony dot steelandt (at) bucodi dot com Visit the python blog at http://360.yahoo.com/bucodi From max at alcyone.com Thu Jun 1 12:25:23 2006 From: max at alcyone.com (Erik Max Francis) Date: Thu, 01 Jun 2006 03:25:23 -0700 Subject: shuffling elements of a list In-Reply-To: <69ft72516amvri3up8fop5rf543s6en1lg@4ax.com> References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> <1149051212.139046.155340@c74g2000cwc.googlegroups.com> <1149105576.321676.131600@j55g2000cwa.googlegroups.com> <69ft72516amvri3up8fop5rf543s6en1lg@4ax.com> Message-ID: David C. Ullrich wrote: > Good example, because we know that EMF is not dumb. I've seen > the same algorithm many times - the best example is ... Man, an error made _six years ago_ and people are still bringing it up ... -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis The purpose of man's life is not happiness but worthiness. -- Felix Adler From bnblazer at gmail.com Thu Jun 1 12:29:35 2006 From: bnblazer at gmail.com (Brian) Date: 1 Jun 2006 03:29:35 -0700 Subject: TSV to HTML In-Reply-To: References: <1149098823.979329.9220@f6g2000cwb.googlegroups.com> <447e268a$0$3699$4d3efbfe@news.sover.net> <1149126509.984331.306530@h76g2000cwa.googlegroups.com> Message-ID: <1149157775.490474.173970@y43g2000cwc.googlegroups.com> Dennis, Thank you for that response. Your code was very helpful to me. I think that actually seeing how it should be done in Python was a lot more educational than spending hours with trial and error. One question (and this is a topic that I still have trouble getting my arms around). Why is the text in STYLEBLOCK tripple quoted? Thanks again, Brian From grflanagan at yahoo.co.uk Thu Jun 1 12:37:10 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 1 Jun 2006 03:37:10 -0700 Subject: shuffling elements of a list References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> <1149147164.012044.66960@u72g2000cwu.googlegroups.com> Message-ID: <1149158230.815685.167850@i39g2000cwa.googlegroups.com> Peter Otten wrote: > Gerard Flanagan wrote: > > > Ben Finney wrote: > > >> pile_index = 0 > >> for card in deck: > >> piles[pile_index].append(card) > >> pile_index = (pile_index + 1) % numpiles > >> > > > > no need to maintain an index ;-) > > > > piles = [ list() for _ in range(n) ] > > for i, card in enumerate(deck): > > piles[i % numpiles].append(card) > > No need to maintain an index ;-) > > piles = [deck[start::numpiles] for start in range(numpiles)] I am humbled :-) Gerard From duncan.booth at invalid.invalid Thu Jun 1 12:44:29 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 Jun 2006 10:44:29 GMT Subject: what is the reasonable (best?) Exception handling strategy? References: <1149156321.440828.95150@g10g2000cwb.googlegroups.com> Message-ID: Petr Jakes wrote: > I am a little bit confused by all possibilities for exceptions handling > in Python (probably because I am not skilled enough??) I did try to > search trough this list and reading Python tutorial about Errors and > Exceptions but didn't find some "general" answer about exception > handling policy (strategy). It depends on what you are actually able to do about the exception. If you can recover from it meaningfully then you may want to handle it near the place it is thrown. If all you can do is abort the entire program then you handle that at the outermost level of the program. > > In the following example each row can IMHO raise an exception (if the > Firebird service is not running for example, if the database is > corrupted etc.). If a service isn't running that sounds pretty fatal. Handle it at the outer levels of your code. If the database is corrupted that might also be terminal unless you include bad data (e.g. invalid email address) in that definition, in that case it may be something you can fix, ignore, or live with: it should be obvious in this case where in your code you need to do the fixup or ignoring. > > Do I have to write "try/except" clause on each row? The processing you perform on a row might raise an exception for which the correct action would be to simply continue with the next row. In that case handle the exception inside the 'processRow' function so the code which iterates over the rows never sees it. If it is a more serious problem which is going to stop you processing any further rows then you let it propogate. > > Or to write try/except block (function) where to handle (on one place) > all exceptions expected in the program code is a good idea? > > Or do I have to write own "exception hook"? > > What about unexpected exceptions? :( Big errors, or unexpected errors you handle in one place usually by making sure a human is alerted to the problem. From fabiofz at gmail.com Thu Jun 1 12:46:51 2006 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Thu, 1 Jun 2006 07:46:51 -0300 Subject: Best Python Editor In-Reply-To: <1149149668.113003.142940@j55g2000cwa.googlegroups.com> References: <1149149668.113003.142940@j55g2000cwa.googlegroups.com> Message-ID: On 1 Jun 2006 01:14:28 -0700, andyrsmith at googlemail.com < andyrsmith at googlemail.com> wrote: > > If we could go back to emacs again for a second... > > I'm still using emacs but have been playing with a few other ide's > (wing, komodo + pydev) are the ones i've given a go recently. > > However I still end up coming back to emacs for what I consider to be > emacs mode's piece of 'killer functionality', (well, killer for me > anyway :-) ) which is the C-c C-c shortcut to send the contents of the > current buffer to a running interpreter. (i.e. one long-running > interpreter that behaves as if the entire buffer had been retyped). > Have you checked pydev extensions? It has an 'interactive console' which can do what you just said (but different keybinding, as it would require you to select all you want: Ctrl+A and then send it to the buffer: Ctrl+Enter, but on the other hand, it can do much more too) You can check details at http://www.fabioz.com/pydev/manual_adv_interactive_console.html If there's something missing there, you can submit a feature-request... Cheers, Fabio -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/python-list/attachments/20060601/23185d25/attachment.html From osv at javad.com Thu Jun 1 12:53:32 2006 From: osv at javad.com (Sergei Organov) Date: Thu, 01 Jun 2006 14:53:32 +0400 Subject: Watching serial port activity. References: <1148955873.334359.47860@u72g2000cwu.googlegroups.com> <127ncut3mpadoc5@corp.supernews.com> <1148962019.355956.124420@38g2000cwa.googlegroups.com> <127oj612scnl8a0@corp.supernews.com> <1148998176.105881.156310@g10g2000cwb.googlegroups.com> <127olia8pnldl90@corp.supernews.com> <127rccueg04oie5@corp.supernews.com> Message-ID: Grant Edwards writes: > On 2006-05-31, Sergei Organov wrote: > >> It seems that sniff on a real tty device could be implemented using the >> same technique strace uses to intercept and show syscalls, though I'm >> not aware of any sniffer application that does it. > > Using strace you can indeed trace read/write calls on user-specified > file descriptors. I've actually meant to take strace in source code and modify it for particular purpose. The fact that it almost can do it in unmodified form is quite impressive though. > Figuring out which file descriptors to trace is the tricky part. Provided I have port name, say, /dev/ttyM0, and have running application: osv at osv ~$ fuser /dev/ttyM0 /dev/ttyM0: 5134 osv at osv ~$ ls -l /proc/5134/fd | grep /dev/ttyM0 lrwx------ 1 osv osv 64 2006-05-29 15:33 8 -> /dev/ttyM0 osv at osv ~$ so I need to track fd #8 of the process with pid 5134. Guess one can attach to a running process as gdb does it. Alternatively, if the process to be sniffed sporadically opens/closes the port at run-time, it is required to track open()/close() syscalls as well as read()/write() ones, I think. Overall, seems not that trivial but doable. -- Sergei. From eric_brunel at despammed.com Thu Jun 1 13:12:18 2006 From: eric_brunel at despammed.com (Eric Brunel) Date: Thu, 01 Jun 2006 13:12:18 +0200 Subject: Function mistaken for a method Message-ID: Hi all, I just stepped on a thing that I can't explain. Here is some code showing the problem: ----------------------------- class C: f = None def __init__(self): if self.f is not None: self.x = self.f(0) else: self.x = 0 class C1(C): f = int class C2(C): f = lambda x: x != 0 o1 = C1() print o1.x o2 = C2() print o2.x ----------------------------- Basically, I want an optional variant function across sub-classes of the same class. I did it like in C1 for a start, then I needed something like C2. The result is... surprising: 0 Traceback (most recent call last): File "func-vs-meth.py", line 18, in ? o2 = C2() File "func-vs-meth.py", line 5, in __init__ self.x = self.f(0) TypeError: () takes exactly 1 argument (2 given) So the first works and o1.x is actually 0. But the second fails because self is also being passed as the first argument to the lambda. Defining a "real" function doesn't help: the error is the same. My actual question is: why does it work in one case and not in the other? As I see it, int is just a function with one parameter, and the lambda is just another one. So why does the first work, and not the second? What 'black magic' takes place so that int is not mistaken for a method in the first case? -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From maric at aristote.info Thu Jun 1 13:29:14 2006 From: maric at aristote.info (Maric Michaud) Date: Thu, 1 Jun 2006 13:29:14 +0200 Subject: Function mistaken for a method In-Reply-To: References: Message-ID: <200606011329.15661.maric@aristote.info> Le Jeudi 01 Juin 2006 13:12, Eric Brunel a ?crit : > class C1(C): > f = int int is not a function but a type, but it's callable so int(0) return 0. > class C2(C): > f = lambda x: x != 0 lambda is a function, applied as a class attribute it becomes a method so it's called with a first parameter representing the instance, self.f(0) in the __init__ becomes C2.f(self, 0), so the lambda should be : f = lambda s, x: x != 0 # s for self, some poeple use _ this exactly the same as : def f(self, val) : return x != 0 (that lambda will return True or False i expect this is not what you want) -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From maric at aristote.info Thu Jun 1 13:33:38 2006 From: maric at aristote.info (Maric Michaud) Date: Thu, 1 Jun 2006 13:33:38 +0200 Subject: Function mistaken for a method In-Reply-To: <200606011329.15661.maric@aristote.info> References: <200606011329.15661.maric@aristote.info> Message-ID: <200606011333.38780.maric@aristote.info> Le Jeudi 01 Juin 2006 13:29, Maric Michaud a ?crit?: > this exactly the same as : > > ? ?def f(self, val) : > ? ? ? ?return x != 0 oops, def f(self, val) : return val != 0 -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From __peter__ at web.de Thu Jun 1 13:34:53 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Jun 2006 13:34:53 +0200 Subject: Function mistaken for a method References: Message-ID: Eric Brunel wrote: > My actual question is: why does it work in one case and not in the other? > As I see it, int is just a function with one parameter, and the lambda is > just another one. So why does the first work, and not the second? What > 'black magic' takes place so that int is not mistaken for a method in the > first case? A python-coded function has a __get__ attribute, a C-function doesn't. Therefore C1.f performs just the normal attribute lookup while C2.f also triggers the f.__get__(C2(), C2) call via the descriptor protocol which happens to return a bound method. Peter From maric at aristote.info Thu Jun 1 13:46:16 2006 From: maric at aristote.info (Maric Michaud) Date: Thu, 1 Jun 2006 13:46:16 +0200 Subject: Function mistaken for a method In-Reply-To: References: Message-ID: <200606011346.17442.maric@aristote.info> Le Jeudi 01 Juin 2006 13:34, Peter Otten a ?crit?: > A python-coded function has a __get__ attribute, a C-function doesn't. > Therefore C1.f performs just the normal attribute lookup while C2.f also > triggers the f.__get__(C2(), C2) call via the descriptor protocol which > happens to return a bound method. I don't think it's about c-coded versus python-coded stuff, C1.f is a type, C2.f is a method. In [14]: class t : pass ....: In [15]: class u : ....: f = t ....: ....: In [16]: u().f() Out[16]: <__main__.t instance at 0xa795a9ec> -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From onurb at xiludom.gro Thu Jun 1 13:49:18 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 01 Jun 2006 13:49:18 +0200 Subject: How do you practice Python? In-Reply-To: <1149152214.215907.31800@i39g2000cwa.googlegroups.com> References: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> <447eaae0$0$20867$636a55ce@news.free.fr> <1149152214.215907.31800@i39g2000cwa.googlegroups.com> Message-ID: <447ed4b1$0$20866$626a54ce@news.free.fr> Ray wrote: > bruno at modulix wrote: > >>>In our field, we don't always get to program in the language we'd like >>>to program. So... how do you practice Python in this case? Say you're >>>doing J2EE right now. >> >>Hopefully not ! > > > I am :-( > Can we do something to help you out of this bad situation ? (sorry...) >>>How do you practice Python to keep your skills >>>sharp? >> >>How *would* I do ? Well, perhaps I'd use Jython ? > > > Um, I mean, what if you have to use something other than > Python/Jython/IronPython? :) Ruby or Smalltalk, then ? No ? J2EE ? Argh ! (me run away) > How do you keep your Python skill sharp? Just by thinking about how I would solve the problem at hand in Python - and then cry :( -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From noway at sorry.com Thu Jun 1 13:52:56 2006 From: noway at sorry.com (Giovanni Bajo) Date: Thu, 01 Jun 2006 11:52:56 GMT Subject: struct: type registration? References: <447e4b98$1@news.eftel.com> Message-ID: John Machin wrote: >> given the ongoing work on struct (which I thought was a dead >> module), I was wondering if it would be possible to add an API to >> register custom parsing codes for struct. Whenever I use it for >> non-trivial tasks, I always happen to write small wrapper functions >> to adjust the values returned by struct. >> >> An example API would be the following: >> >> ============================================ >> def mystring_len(): >> return 20 >> >> def mystring_pack(s): >> if len(s) > 20: >> raise ValueError, "a mystring can be at max 20 chars" >> s = (s + "\0"*20)[:20] > > Have you considered s.ljust(20, "\0") ? Right. This happened to be an example... >> s = struct.pack("20s", s) >> return s > > I am an idiot, so please be gentle with me: I don't understand why you > are using struct.pack at all: Because I want to be able to parse largest chunks of binary datas with custom formatting. Did you miss the whole point of my message: struct.unpack("3liiSiiShh", data) You need struct.unpack() to parse these datas, and you need custom packer/unpacker to avoid post-processing the output of unpack() just because it just knows of basic Python types. In binary structs, there happen to be *types* which do not map 1:1 to Python types, nor they are just basic C types (like the ones struct supports). Using custom formatter is a way to better represent these types (instead of mapping them to the "most similar" type, and then post-process it). In my example, "S" is a basic-type which is a "A 0-terminated 20-byte string", and expressing it in the struct format with the single letter "S" is more meaningful in my code than using "20s" and then post-processing the resulting string each and every time this happens. >>>>> import struct >>>>> x = ("abcde" + "\0" * 20)[:20] >>>>> x > 'abcde\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' >>>>> len(x) > 20 >>>>> y = struct.pack("20s", x) >>>>> y == x > True >>>>> > > Looks like a big fat no-op to me; you've done all the heavy lifting > yourself. Looks like you totally misread my message. Your string "x" is what I find in binary data, and I need to *unpack* into a regular Python string, which would be "abcde". > >> idx = s.find("\0") >> if idx >= 0: >> s = s[:idx] >> return s > > Have you considered this: > >>>>> z.rstrip("\0") > 'abcde' This would not work because, in the actual binary data I have to parse, only the first \0 is meaningful and terminates the string (like in C). There is absolutely no guarantees that the rest of the padding is made of \0s as well. -- Giovanni Bajo From __peter__ at web.de Thu Jun 1 14:03:27 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Jun 2006 14:03:27 +0200 Subject: Function mistaken for a method References: Message-ID: Maric Michaud wrote: > Le Jeudi 01 Juin 2006 13:34, Peter Otten a ?crit?: >> A python-coded function has a __get__ attribute, a C-function doesn't. >> Therefore C1.f performs just the normal attribute lookup while C2.f also >> triggers the f.__get__(C2(), C2) call via the descriptor protocol which >> happens to return a bound method. > I don't think it's about c-coded versus python-coded stuff, C1.f is a > type, C2.f is a method. You are right, int is a type not a function, but presence (and implementation, of course) of __get__ is still the distinguishing factor: >>> class Int(int): ... class __metaclass__(type): ... def __get__(*args): print "XXX", args ... >>> class C: ... int = Int ... >>> C().int XXX (, <__main__.C instance at 0x402948cc>, ) Also: >>> from math import sin >>> sin >>> def son(x): pass ... >>> class C: ... sin = sin ... son = son ... >>> C().sin(0) 0.0 >>> C().son(0) Traceback (most recent call last): File "", line 1, in ? TypeError: son() takes exactly 1 argument (2 given) Peter From onurb at xiludom.gro Thu Jun 1 14:01:04 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 01 Jun 2006 14:01:04 +0200 Subject: How do you practice programming? In-Reply-To: <1149152428.348192.106970@h76g2000cwa.googlegroups.com> References: <1149151097.741307.79440@f6g2000cwb.googlegroups.com> <447eabee$0$19567$636a55ce@news.free.fr> <1149152428.348192.106970@h76g2000cwa.googlegroups.com> Message-ID: <447ed774$0$12371$626a54ce@news.free.fr> Ray wrote: > bruno at modulix wrote: > >>1/ programming >>2/ programming >>3/ lurking here, reading posts and sometimes trying to answer, reading >>source code of the oss apps/frameworks I'm working with, searching >>practical solutions in the cookbook etc >>4/ programming > > > Yeah, but that's what most of us are doing too, we are programmers > after all. But you know, it's like a boxer cannot get better just by > going into a lot of fights, he needs good instruction from a good > coach. I learned the guitar mostly by watching other guitarists (good and bad ones), trying to teach whoever asked me what I already knew, and practicing many hours a day (until my fingers hurt too much in fact). In programming, like in any other form of art - and like in spirituality for that matters - *everyone* can be your master - sometimes without even being aware of it - if you let him teach you. > So what would you do? (I guess it's your number #3 above). The #3 only would not be of any use without at least the #1, the #2 and the #4. But I admit that #1, #2 and #4 would be equally useless without the #3 !-) How, and yes, also : using one's head - not only to wear a hat - may be of some help too. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From sjmachin at lexicon.net Thu Jun 1 14:03:28 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 01 Jun 2006 22:03:28 +1000 Subject: Function mistaken for a method In-Reply-To: References: Message-ID: <447ED790.20101@lexicon.net> On 1/06/2006 9:46 PM, Maric Michaud wrote: > Le Jeudi 01 Juin 2006 13:34, Peter Otten a ?crit : >> A python-coded function has a __get__ attribute, a C-function doesn't. >> Therefore C1.f performs just the normal attribute lookup while C2.f also >> triggers the f.__get__(C2(), C2) call via the descriptor protocol which >> happens to return a bound method. > I don't think it's about c-coded versus python-coded stuff, C1.f is a type, > C2.f is a method. > Try putting f = chr (a C function); it behaves like int, not like a 1-arg Python function. See below. Cheers, John C:\junk>type func_meth.py class C: f = None def __init__(self): if self.f is not None: self.x = self.f(0) else: self.x = 99 # differs from int(0) :-) class C1(C): f = int class C2(C): def f(self, arg): return arg != 0 class C3(C): pass class C4(C): f = chr for cls in (C1, C2, C3, C4): o = cls() print "callable: %r; result: %r" % (o.f, o.x) C:\junk>func_meth.py callable: ; result: 0 callable: >; result: False callable: None; result: 99 callable: ; result: '\x00' C:\junk> From aljosa.mohorovic at gmail.com Thu Jun 1 14:09:14 2006 From: aljosa.mohorovic at gmail.com (aljosa) Date: 1 Jun 2006 05:09:14 -0700 Subject: py2exe & qt4/qimage Message-ID: <1149163754.826678.95920@h76g2000cwa.googlegroups.com> i'm trying to convert python (image resizer script using PyQt4) script to exe but support for jpeg and tiff image formats is located in Qt4.1\plugins\imageformats (dll files) and when script is converted exe file doesn't support jpeg and tiff. i tryed using all file formats in script: tmp1 = QImage('images/type.bmp') tmp2 = QImage('images/type.gif') tmp3 = QImage('images/type.jpg') tmp4 = QImage('images/type.png') tmp5 = QImage('images/type.tif') but it doesn't work when i convert script to exe. any tips on howto include jpeg and tiff image formats support in exe? From frithiof.jensen at die_spammer_die.ericsson.com Thu Jun 1 14:03:58 2006 From: frithiof.jensen at die_spammer_die.ericsson.com (Frithiof Andreas Jensen) Date: Thu, 1 Jun 2006 14:03:58 +0200 Subject: creating a new database with mysqldb References: Message-ID: "John Salerno" wrote in message news:gcKag.2113$No6.46302 at news.tufts.edu... > Since the connect method of mysqldb requires a database name, it seems > like you can't use it without having a database already created. The web hotel I use create *one* database together with the account. I.O.W: I cannot create any databases; I can create/delete as many tables as I like within the database (up to the disk space that I have). This is pretty normal, I think. From alanalan at newsgroup.nospam Thu Jun 1 14:11:32 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 1 Jun 2006 08:11:32 -0400 Subject: DB-API: how can I find the column names in a cursor? Message-ID: Hi I use a code similar to this to retrieve data from Oracle database: import cx_Oracle con = cx_Oracle.connect("me/secret at tns") cur = con.cursor() outcur = con.cursor() cur.execute(""" BEGIN MyPkg.MyProc(:cur); END;""", cur=outcur) for row in out_cur: print row The problem is I don't know how to find out what are the column name and type that comes out of query (each row in cursor). Is there any possibility that my Python code can find out the column name and type in each row in cursor? The other problem is accessing data in each row by column name. In Ruby I can say: Print row["ColName"] In Python; however, I must access to row contents by integer index, like PRINT ROW[0], which reduces my program's readability. Can I access to row's contents by column name? Any help would be appreciated, Alan From vadim.feelsgood at gmail.com Thu Jun 1 14:26:31 2006 From: vadim.feelsgood at gmail.com (vadim.feelsgood at gmail.com) Date: 1 Jun 2006 05:26:31 -0700 Subject: Best Python Editor In-Reply-To: <1149149773.999940.13500@i40g2000cwc.googlegroups.com> References: <1149149773.999940.13500@i40g2000cwc.googlegroups.com> Message-ID: <1149164791.002020.210000@c74g2000cwc.googlegroups.com> I use WingIDE too. It is very convenient. Good auto-completion feature. It is not so heavy as Komodo. WingIDE was my the second step after Komodo. Just try it and u'll understand how it is good. yairchu at gmail.com wrote: > > Can anyone tell me a good python editor/IDE? > > It would be great if you can provide the download link also. > > WingIDE is very good. > It gives very nice completions and has a nice thing called "source > assistant" that shows the help of the function you're standing on and > etc. > But I don't think it's open-source and freei if that bothers you > http://www.wingware.com/ > > Another good one is idlespoon. > this one is open-source and freei > http://idlespoon.python-hosting.com/ From onurb at xiludom.gro Thu Jun 1 14:27:05 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 01 Jun 2006 14:27:05 +0200 Subject: Function mistaken for a method In-Reply-To: References: Message-ID: <447edd8d$0$2135$636a55ce@news.free.fr> Peter Otten wrote: > Eric Brunel wrote: > > >>My actual question is: why does it work in one case and not in the other? >>As I see it, int is just a function with one parameter, and the lambda is >>just another one. So why does the first work, and not the second? What >>'black magic' takes place so that int is not mistaken for a method in the >>first case? > > > A python-coded function has a __get__ attribute, a C-function doesn't. > Therefore C1.f performs just the normal attribute lookup while C2.f also > triggers the f.__get__(C2(), C2) call via the descriptor protocol which > happens to return a bound method. FWIW: class Obj(object): def __new__(cls, val, *args, **kw): print "in Obj.__new__" print "- called with :" print " cls :", cls print " val :", val print " args:", str(args) print " kw :", kw obj = object.__new__(cls, *args, **kw) print "got : %s - %s" % (obj, dir(obj)) return obj class CPlus(C): f = Obj > Peter > > -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From m.yanowitz at kearfott.com Thu Jun 1 14:31:34 2006 From: m.yanowitz at kearfott.com (Michael Yanowitz) Date: Thu, 1 Jun 2006 08:31:34 -0400 Subject: Tkinter - changing existing Dialog? In-Reply-To: <447ED790.20101@lexicon.net> Message-ID: Hello: I have a Tkinter GUI Dialog with many buttons and labels and text widgets. What I would like to do is, can I: 1) Disable/deactivate/hide a button, text widget that is already drawn (and of course the opposite enable/activate/show it)? 2) Change the text of a label or button that is already drawn? based on actions taken by the user. Can it be done without destroying the present dialog or the objects in it and creating a new one? Sorry for what probably is such a trivial and basic question. I just can't find the answer or know what the technical term for what I want to do is to search for it myself. Thanks in advance: Michael Yanowitz From codecraig at gmail.com Thu Jun 1 14:30:32 2006 From: codecraig at gmail.com (abcd) Date: 1 Jun 2006 05:30:32 -0700 Subject: PythonDoc Ant Task Message-ID: <1149165032.870017.254980@i40g2000cwc.googlegroups.com> Anyone ever use the PythonDoc ant task? I have the following... ...this is a cut out of the build xml i am using...but it shows the relevant parts. Anyways I can run my "pyDoc" target and it runs successful with no errors. a "docs" directory is created but is empty. Any idea as to why? My "src" folder contains a python file, Foo.py. which looks like this class Bar: def printMe(self): """This method prints my data""" print "some data is being printed" ...Thanks in advance. From eric_brunel at despammed.com Thu Jun 1 14:37:33 2006 From: eric_brunel at despammed.com (Eric Brunel) Date: Thu, 01 Jun 2006 14:37:33 +0200 Subject: Function mistaken for a method References: Message-ID: On Thu, 01 Jun 2006 13:34:53 +0200, Peter Otten <__peter__ at web.de> wrote: > Eric Brunel wrote: > >> My actual question is: why does it work in one case and not in the >> other? >> As I see it, int is just a function with one parameter, and the lambda >> is >> just another one. So why does the first work, and not the second? What >> 'black magic' takes place so that int is not mistaken for a method in >> the >> first case? > A python-coded function has a __get__ attribute, a C-function doesn't. > Therefore C1.f performs just the normal attribute lookup while C2.f also > triggers the f.__get__(C2(), C2) call via the descriptor protocol which > happens to return a bound method. Thanks for your explanations, Peter. I'll have to find another way to do what I want... -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From noway at sorry.com Thu Jun 1 14:35:16 2006 From: noway at sorry.com (Giovanni Bajo) Date: Thu, 01 Jun 2006 12:35:16 GMT Subject: struct: type registration? References: <447e4b98$1@news.eftel.com> Message-ID: <8aBfg.20673$cX1.313575@twister2.libero.it> Giovanni Bajo wrote: > You need struct.unpack() to parse these datas, and you need custom > packer/unpacker to avoid post-processing the output of unpack() just > because it just knows of basic Python types. In binary structs, there > happen to be *types* which do not map 1:1 to Python types, nor they > are just basic C types (like the ones struct supports). Using custom > formatter is a way to better represent these types (instead of > mapping them to the "most similar" type, and then post-process it). > > In my example, "S" is a basic-type which is a "A 0-terminated 20-byte > string", and expressing it in the struct format with the single > letter "S" is more meaningful in my code than using "20s" and then > post-processing the resulting string each and every time this happens. Another compelling example is the SSH protocol: http://www.openssh.com/txt/draft-ietf-secsh-architecture-12.txt Go to section 4, "Data Type Representations Used in the SSH Protocols", and it describes the data types used by the SSH protocol. In a perfect world, I would write some custom packers/unpackers for those types which struct does not handle already (like the "mpint" format), so that I could use struct to parse and compose SSH messages. What I ended up doing was writing a new module sshstruct.py from scratch, which duplicates struct's work, just because I couldn't extend struct. Some examples: client.py: cookie, server_algorithms, guess, reserverd = sshstruct.unpack("16b10LBu", data[1:]) client.py: prompts = sshstruct.unpack("sssu" + "sB"*num_prompts, pkt[1:]) connection.py: pkt = sshstruct.pack("busB", SSH_MSG_CHANNEL_REQUEST, self.recipient_number, type, reply) + custom kex.py: self.P, self.G = sshstruct.unpack("mm",pkt[1:]) Notice for instance how "s" is a SSH string and unpacks directly to a Python string, and "m" is a SSH mpint (infinite precision integer) but unpacks directly into a Python long. Using struct.unpack() this would have been impossible and would have required much post-processing. Actually, another thing that struct should support to cover the SSH protocol (and many other binary protocols) is the ability to parse strings whose size is not known at import-time (variable-length data types). For instance, type "string" in the SSH protocol is a string prepended with its size as uint32. So it's actual size depends on each instance. For this reason, my sshstruct did not have the equivalent of struct.calcsize(). I guess that if there's a way to extend struct, it would comprehend variable-size data types (and calcsize() would return -1 or raise an exception). -- Giovanni Bajo From sjmachin at lexicon.net Thu Jun 1 14:37:16 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 01 Jun 2006 22:37:16 +1000 Subject: struct: type registration? In-Reply-To: References: <447e4b98$1@news.eftel.com> Message-ID: <447EDF7C.3080104@lexicon.net> On 1/06/2006 9:52 PM, Giovanni Bajo wrote: > John Machin wrote: > >>> given the ongoing work on struct (which I thought was a dead >>> module), I was wondering if it would be possible to add an API to >>> register custom parsing codes for struct. Whenever I use it for >>> non-trivial tasks, I always happen to write small wrapper functions >>> to adjust the values returned by struct. >>> >>> An example API would be the following: >>> >>> ============================================ >>> def mystring_len(): >>> return 20 >>> >>> def mystring_pack(s): >>> if len(s) > 20: >>> raise ValueError, "a mystring can be at max 20 chars" >>> s = (s + "\0"*20)[:20] >> Have you considered s.ljust(20, "\0") ? > > Right. This happened to be an example... > >>> s = struct.pack("20s", s) >>> return s >> I am an idiot, so please be gentle with me: I don't understand why you >> are using struct.pack at all: Given a choice between whether I was referring to the particular instance of using struct.pack two lines above, or whether I was doubting the general utility of the struct module, you appear to have chosen the latter, erroneously. > > Because I want to be able to parse largest chunks of binary datas with custom > formatting. Did you miss the whole point of my message: No. > > struct.unpack("3liiSiiShh", data) > > You need struct.unpack() to parse these datas, and you need custom > packer/unpacker to avoid post-processing the output of unpack() just because it > just knows of basic Python types. In binary structs, there happen to be *types* > which do not map 1:1 to Python types, nor they are just basic C types (like the > ones struct supports). Using custom formatter is a way to better represent > these types (instead of mapping them to the "most similar" type, and then > post-process it). > > In my example, "S" is a basic-type which is a "A 0-terminated 20-byte string", > and expressing it in the struct format with the single letter "S" is more > meaningful in my code than using "20s" and then post-processing the resulting > string each and every time this happens. > > >>>>>> import struct >>>>>> x = ("abcde" + "\0" * 20)[:20] >>>>>> x >> 'abcde\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' >>>>>> len(x) >> 20 >>>>>> y = struct.pack("20s", x) >>>>>> y == x >> True >> Looks like a big fat no-op to me; you've done all the heavy lifting >> yourself. > > Looks like you totally misread my message. Not at all. Your function: def mystring_pack(s): if len(s) > 20: raise ValueError, "a mystring can be at max 20 chars" s = (s + "\0"*20)[:20] s = struct.pack("20s", s) return s can be even better replaced by (after reading the manual "For packing, the string is truncated or padded with null bytes as appropriate to make it fit.") by: def mystring_pack(s): if len(s) > 20: raise ValueError, "a mystring can be at max 20 chars" return s # return s = (s + "\0"*20)[:20] # not needed, according to the manual # s = struct.pack("20s", s) # As I said, this particular instance of using struct.pack is a big fat no-op. > Your string "x" is what I find in > binary data, and I need to *unpack* into a regular Python string, which would > be "abcde". > And you unpack it with a custom function that also contains a fat no-op: def mystring_unpack(s): assert len(s) == 20 s = struct.unpack("20s", s)[0] # does nothing idx = s.find("\0") if idx >= 0: s = s[:idx] return s > >>> idx = s.find("\0") >>> if idx >= 0: >>> s = s[:idx] >>> return s >> Have you considered this: >> >>>>>> z.rstrip("\0") >> 'abcde' > > > This would not work because, in the actual binary data I have to parse, only > the first \0 is meaningful and terminates the string (like in C). There is > absolutely no guarantees that the rest of the padding is made of \0s as well. Point taken. Cheers, John From maric at aristote.info Thu Jun 1 14:44:37 2006 From: maric at aristote.info (Maric Michaud) Date: Thu, 1 Jun 2006 14:44:37 +0200 Subject: Function mistaken for a method In-Reply-To: References: Message-ID: <200606011444.38612.maric@aristote.info> Le Jeudi 01 Juin 2006 13:12, Eric Brunel a ?crit?: > Thanks for your explanations, Peter. I'll have to find another way to do ? > what I want... maybe : class C: ? ?f = None ? ?def __init__(self): ? ? ?if self.f is not None: ? ? ? ?self.x = self.f(0) ? ? ?else: ? ? ? ?self.x = 0 class C2(C): ? ?def __init__(self) : self.f = lambda x: x != 0 -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From sjmachin at lexicon.net Thu Jun 1 14:40:37 2006 From: sjmachin at lexicon.net (John Machin) Date: 1 Jun 2006 05:40:37 -0700 Subject: Tkinter - changing existing Dialog? In-Reply-To: References: <447ED790.20101@lexicon.net> Message-ID: <1149165637.162492.139380@j55g2000cwa.googlegroups.com> Michael Yanowitz wrote: > Hello: > > > I have a Tkinter GUI Dialog with many buttons and labels and text > widgets. > So start a *new* thread. From iainking at gmail.com Thu Jun 1 14:48:16 2006 From: iainking at gmail.com (Iain King) Date: 1 Jun 2006 05:48:16 -0700 Subject: Trying to get FreeImagePy to work. In-Reply-To: References: <1148651668.578852.3160@i40g2000cwc.googlegroups.com> <7fEdg.13375$cX1.201311@twister2.libero.it> <1148655611.990937.322350@j73g2000cwa.googlegroups.com> Message-ID: <1149166096.176405.22780@i40g2000cwc.googlegroups.com> Michele Petrazzo wrote: > Iain King wrote: > > Michele Petrazzo wrote: > > > > I downloaded and installed 0.9.9.3, and it now works. Thanks! > > > > I advice you to don't use that ctypes version... Better is to use the > newest one and update freeimagepy! > > > Iain > > > > Michele OK, Ive installed the latest versions I can find, which are FreeImagePy 1.2.4 and ctypes 0.9.9.6, and I'm back to the error I had earlier. Do you know what's wrong? Iain From reply.in.the.newsgroup at my.address.is.invalid Thu Jun 1 14:49:33 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Thu, 01 Jun 2006 14:49:33 +0200 Subject: what is the reasonable (best?) Exception handling strategy? References: <1149156321.440828.95150@g10g2000cwb.googlegroups.com> Message-ID: Petr Jakes: >What about unexpected exceptions? :( I asked a similar question some time ago: http://groups.google.nl/group/comp.lang.python/browse_thread/thread/25963b99da4b2653 -- Ren? Pijlman From __peter__ at web.de Thu Jun 1 14:51:09 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Jun 2006 14:51:09 +0200 Subject: Function mistaken for a method References: Message-ID: Eric Brunel wrote: > On Thu, 01 Jun 2006 13:34:53 +0200, Peter Otten <__peter__ at web.de> wrote: > >> Eric Brunel wrote: >> >>> My actual question is: why does it work in one case and not in the >>> other? >>> As I see it, int is just a function with one parameter, and the lambda >>> is >>> just another one. So why does the first work, and not the second? What >>> 'black magic' takes place so that int is not mistaken for a method in >>> the >>> first case? >> A python-coded function has a __get__ attribute, a C-function doesn't. >> Therefore C1.f performs just the normal attribute lookup while C2.f also >> triggers the f.__get__(C2(), C2) call via the descriptor protocol which >> happens to return a bound method. > > Thanks for your explanations, Peter. I'll have to find another way to do > what I want... Maybe just class C2(C): f?=?staticmethod(lambda?x:?x?!=?0) Peter From fredrik at pythonware.com Thu Jun 1 14:54:16 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 1 Jun 2006 14:54:16 +0200 Subject: DB-API: how can I find the column names in a cursor? References: Message-ID: "A.M" wrote: > The problem is I don't know how to find out what are the column name and type that comes out of > query (each row in cursor). > > Is there any possibility that my Python code can find out the column name and type in each row in > cursor? >From "cursor objects" in the DB-API documentation: .description "This read-only attribute is a sequence of 7-item sequences. Each of these sequences contains information describing one result column: (name, type_code, display_size, internal_size, precision, scale, null_ok). The first two items (name and type_code) are mandatory, the other five are optional and must be set to None if meaningfull values are not provided." The full spec is available here: http://www.python.org/dev/peps/pep-0249/ From onurb at xiludom.gro Thu Jun 1 15:07:26 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 01 Jun 2006 15:07:26 +0200 Subject: Function mistaken for a method In-Reply-To: References: Message-ID: <447ee701$0$22029$626a54ce@news.free.fr> Eric Brunel wrote: > Hi all, > > I just stepped on a thing that I can't explain. Here is some code > showing the problem: > > ----------------------------- > class C: Do yourself a favour : use new-style classes. class C(object) > f = None > def __init__(self): > if self.f is not None: > self.x = self.f(0) > else: > self.x = 0 > > class C1(C): > f = int > > class C2(C): > f = lambda x: x != 0 > > o1 = C1() > print o1.x > > o2 = C2() > print o2.x > ----------------------------- > > Basically, I want an optional variant function across sub-classes of > the same class. > > I did it like in C1 for a start, then I needed > something like C2. The result is... surprising: > > 0 > Traceback (most recent call last): > File "func-vs-meth.py", line 18, in ? > o2 = C2() > File "func-vs-meth.py", line 5, in __init__ > self.x = self.f(0) > TypeError: () takes exactly 1 argument (2 given) Not surprising at all. Functions implement the descriptor protocol[1]. When bound to a class and looked up via an instance, it's the __get__ method of the function object that get called - with the instance as param, as defined by the descriptor protocol. This method then return the function wrapped - with the instance - in an Method object - which itself, when called, returns the result of calling the function *with the instance as first parameter*. Which is how methods can work on the instance, and why one has to explicitly declare the instance parameter in "functions to be used as methods", but not explicitly pass it at call time. (please some guru correct me if I missed something here, but AFAIK it must be a correct enough description of method invocation mechanism in Python). [1] about descriptors, see: http://docs.python.org/ref/descriptors.html http://www.geocities.com/foetsch/python/new_style_classes.htm#descriptors > So the first works and o1.x is actually 0. int is not a function. >>> type(int) int is a type. A Python type is a callable object, and act as a factory for instances of it. If the type doesn't implement the descriptor protocol, when bound to a class and looked up via an instance, normal lookup rules apply. So the type object is returned as is. In your case, since int does'nt implement the descriptor protocol, once looked up (and returned as is), it's called with a correct argument - so everything runs fine. Try this: class Obj(object): def __new__(cls, val, *args, **kw): print "in Obj.__new__" print "- called with :" print " cls :", cls print " val :", val print " args: %s" % str(args) print " kw : %s" % kw obj = object.__new__(cls, *args, **kw) print "got : %s - %s" % (obj, dir(obj)) return obj def __init__(self, *args, **kw): print "in Obj.__init__" print "- called with :" print " args: %s" % str(args) print " kw : %s" % kw class C4(C): f = Obj > But the second fails because > self is also being passed as the first argument to the lambda. Of course. It's a function, and it's bound to a class, and looked up via an instance of the class. Try this: def truc(*args, **kw): print "in truc()__" print "- called with :" print " args: %s" % str(args) print " kw : %s" % kw if len(args) > 1: return args[1] class C6(C): f = truc > Defining > a "real" function doesn't help: the error is the same. What' a "real" function ?-) lambdas *are* real functions. >>> type(lambda x: x) >>> > My actual question is: why does it work in one case and not in the > other? cf above. > As I see it, int is just a function with one parameter, Nope, it's a type. Functions are just one kind of callable. Types are callables too, as are any object overloading the call operator - which is '()' - by implementing the __call__(self, ...) method. class NotAFunc(object): def __call__(self): print "I'm not a function" return 42 func = NotAFunc() func() > and the > lambda is just another one. True. And functions implement the descriptor protocol. > So why does the first work, and not the > second? What 'black magic' takes place so that int is not mistaken for > a method in the first case? cf above. If you understood all my explanations, you now know how to solve the problem. Else, here the solution: class C3(C): f = lambda self, x: return x -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From codecraig at gmail.com Thu Jun 1 15:10:03 2006 From: codecraig at gmail.com (abcd) Date: 1 Jun 2006 06:10:03 -0700 Subject: PythonDoc Ant Task In-Reply-To: <1149165032.870017.254980@i40g2000cwc.googlegroups.com> References: <1149165032.870017.254980@i40g2000cwc.googlegroups.com> Message-ID: <1149167403.532618.22370@y43g2000cwc.googlegroups.com> i found that the problem is because of an import, which is strange. The imported module looks something like this [code] import time class Foo: pass class Bar: global javax.swing import javax.swing [/code] ....so it seems that pydoc cant giggity-giggit! From harry.g.george at boeing.com Thu Jun 1 07:00:28 2006 From: harry.g.george at boeing.com (Harry George) Date: Thu, 1 Jun 2006 05:00:28 GMT Subject: How do you practice Python? References: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> <447eaae0$0$20867$636a55ce@news.free.fr> <1149152214.215907.31800@i39g2000cwa.googlegroups.com> Message-ID: "Ray" writes: > bruno at modulix wrote: > > > In our field, we don't always get to program in the language we'd like > > > to program. So... how do you practice Python in this case? Say you're > > > doing J2EE right now. > > > > Hopefully not ! > > I am :-( > > > > How do you practice Python to keep your skills > > > sharp? > > > > How *would* I do ? Well, perhaps I'd use Jython ? > > Um, I mean, what if you have to use something other than > Python/Jython/IronPython? :) How do you keep your Python skill sharp? > > > -- > > bruno desthuilliers > > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > > p in 'onurb at xiludom.gro'.split('@')])" > Do projects at home. Either find an existing OSS project, or roll your own. Once you have the basics of the language, the skills are domain-specific: XML, GUIs, CAD, gaming, multithreading, numerical analysis, natural language progromming, etc. If you do an existing project, then you benefit from peer reviews and other informal learning opportunities. -- Harry George PLM Engineering Architecture From alanalan at newsgroup.nospam Thu Jun 1 15:20:09 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 1 Jun 2006 09:20:09 -0400 Subject: DB-API: how can I find the column names in a cursor? References: Message-ID: Thank you Fredrik for help. Would you be able to help with the second part of question: The other problem is accessing data in each row by column name. In Ruby I can say: Print row["ColName"] In Python; however, I must access to row contents by integer index, like PRINT ROW[0], which reduces my program's readability. Can I access to row's contents by column name? Thanks again, Alan "Fredrik Lundh" wrote in message news:mailman.6403.1149166487.27775.python-list at python.org... > "A.M" wrote: > >> The problem is I don't know how to find out what are the column name and >> type that comes out of query (each row in cursor). >> >> Is there any possibility that my Python code can find out the column name >> and type in each row in cursor? > >>From "cursor objects" in the DB-API documentation: > > .description > > "This read-only attribute is a sequence of 7-item > sequences. Each of these sequences contains information > describing one result column: (name, type_code, > display_size, internal_size, precision, scale, > null_ok). The first two items (name and type_code) are > mandatory, the other five are optional and must be set to > None if meaningfull values are not provided." > > The full spec is available here: http://www.python.org/dev/peps/pep-0249/ > > > > From chris.cavalaria at free.fr Thu Jun 1 15:36:48 2006 From: chris.cavalaria at free.fr (Christophe) Date: Thu, 01 Jun 2006 15:36:48 +0200 Subject: Function mistaken for a method In-Reply-To: References: Message-ID: <447eed61$0$20860$626a54ce@news.free.fr> Eric Brunel a ?crit : > On Thu, 01 Jun 2006 13:34:53 +0200, Peter Otten <__peter__ at web.de> wrote: > >> Eric Brunel wrote: >> >>> My actual question is: why does it work in one case and not in the >>> other? >>> As I see it, int is just a function with one parameter, and the >>> lambda is >>> just another one. So why does the first work, and not the second? What >>> 'black magic' takes place so that int is not mistaken for a method >>> in the >>> first case? >> >> A python-coded function has a __get__ attribute, a C-function doesn't. >> Therefore C1.f performs just the normal attribute lookup while C2.f also >> triggers the f.__get__(C2(), C2) call via the descriptor protocol which >> happens to return a bound method. > > > Thanks for your explanations, Peter. I'll have to find another way to > do what I want... You have 2 ways to do it already, here's a third : class C: f = None def __init__(self): if self.__class__.f is not None: self.x = self.__class__.f(0) else: self.x = 0 From fredrik at pythonware.com Thu Jun 1 15:41:10 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 1 Jun 2006 15:41:10 +0200 Subject: PythonDoc Ant Task References: <1149165032.870017.254980@i40g2000cwc.googlegroups.com> <1149167403.532618.22370@y43g2000cwc.googlegroups.com> Message-ID: "abcd" wrote: > class Bar: > global javax.swing > import javax.swing > [/code] > > ....so it seems that pydoc cant giggity-giggit! "global javax.swing" is not valid Python syntax. what is that global/import combo supposed to do, and what environment do you run this under ? From micklee74 at hotmail.com Thu Jun 1 15:44:42 2006 From: micklee74 at hotmail.com (micklee74 at hotmail.com) Date: 1 Jun 2006 06:44:42 -0700 Subject: default argument values qns Message-ID: <1149169482.717737.241410@g10g2000cwb.googlegroups.com> hi i have declared a function like this: def aFunction ( arg1 , arg2 = 0): .... print type(arg2) when i try to print the type of arg2, it gives me 'str' type..why is it not integer type, since i have declared it as 0 ?? thanks From python.list at tim.thechases.com Thu Jun 1 15:53:21 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 01 Jun 2006 08:53:21 -0500 Subject: default argument values qns In-Reply-To: <1149169482.717737.241410@g10g2000cwb.googlegroups.com> References: <1149169482.717737.241410@g10g2000cwb.googlegroups.com> Message-ID: <447EF151.2020309@tim.thechases.com> > i have declared a function like this: > > def aFunction ( arg1 , arg2 = 0): > .... > print type(arg2) > > when i try to print the type of arg2, it gives me 'str' > type..why is it not integer type, since i have declared > it as 0 ?? >>> def a(arg1, arg2=0): ... print type(arg2) ... >>> a("something") Looks like it's an int to me. You must be doing something spurious in your mysterious "...." that changes the data type. -tkc From fredrik at pythonware.com Thu Jun 1 15:50:20 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 1 Jun 2006 15:50:20 +0200 Subject: default argument values qns References: <1149169482.717737.241410@g10g2000cwb.googlegroups.com> Message-ID: micklee74 at hotmail.com wrote: > i have declared a function like this: > > def aFunction ( arg1 , arg2 = 0): > .... > print type(arg2) > > when i try to print the type of arg2, it gives me 'str' type..why is it > not integer type, since i have declared it as 0 ?? because you or someone else is passing in a string as the second argument, perhaps? >>> def aFunction(arg1, arg2=0): ... print type(arg2) ... >>> aFunction(1) >>> aFunction(1, 2.0) >>> aFunction(1, "two") From alf at merlin.fayauffre.org Thu Jun 1 15:51:23 2006 From: alf at merlin.fayauffre.org (Alexandre Fayolle) Date: Thu, 1 Jun 2006 13:51:23 +0000 (UTC) Subject: default argument values qns References: <1149169482.717737.241410@g10g2000cwb.googlegroups.com> Message-ID: Le 01-06-2006, micklee74 at hotmail.com nous disait: > hi > i have declared a function like this: > > def aFunction ( arg1 , arg2 = 0): > .... > print type(arg2) > > when i try to print the type of arg2, it gives me 'str' type..why is it > not integer type, since i have > declared it as 0 ?? You probably either called the function with a string as the second argument, or assigned a string to arg2 in the ... part of the function. On my box, I get what you would expect: >>> def aFunction ( arg1 , arg2 = 0): ... print type(arg2) ... >>> aFunction(2) Now, remember that there are no variables in Python, only identifiers, which are refering to values. When you print type(arg2), you are not printing the "type of variable arg2", but the "type of the value referenced by arg2", which is quite different, especially because it can change during the execution of the program. -- Alexandre Fayolle LOGILAB, Paris (France) Formations Python, Zope, Plone, Debian: http://www.logilab.fr/formations D?veloppement logiciel sur mesure: http://www.logilab.fr/services Python et calcul scientifique: http://www.logilab.fr/science From maric at aristote.info Thu Jun 1 15:58:01 2006 From: maric at aristote.info (Maric Michaud) Date: Thu, 1 Jun 2006 15:58:01 +0200 Subject: Function mistaken for a method In-Reply-To: <447eed61$0$20860$626a54ce@news.free.fr> References: <447eed61$0$20860$626a54ce@news.free.fr> Message-ID: <200606011558.02715.maric@aristote.info> Le Jeudi 01 Juin 2006 15:36, Christophe a ?crit?: > ? ? ? ?self.x = self.__class__.f(0) nope, this will result in a TypeError "unbound method must be called with instance as first argument" -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From luismgz at gmail.com Thu Jun 1 15:59:53 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 1 Jun 2006 06:59:53 -0700 Subject: DB-API: how can I find the column names in a cursor? In-Reply-To: References: Message-ID: <1149170393.230636.74000@c74g2000cwc.googlegroups.com> I don't know if it works this way with Oracle, but the python dbpai has the cursor.description method that can help. For example: cur.execute( "your query here" ) columns = [i[0] for i in cur.description] cur.description gives a lot of data about your recordset, and the first field is the column name. Hope this helps... Luis A.M wrote: > Hi > > > > I use a code similar to this to retrieve data from Oracle database: > > > > import cx_Oracle > > > > con = cx_Oracle.connect("me/secret at tns") > > cur = con.cursor() > > outcur = con.cursor() > > cur.execute(""" > > BEGIN > > MyPkg.MyProc(:cur); > > END;""", cur=outcur) > > > > for row in out_cur: > > print row > > > > > > The problem is I don't know how to find out what are the column name and > type that comes out of query (each row in cursor). > > > > Is there any possibility that my Python code can find out the column name > and type in each row in cursor? > > > > The other problem is accessing data in each row by column name. In Ruby I > can say: > > > > Print row["ColName"] > > > > In Python; however, I must access to row contents by integer index, like > PRINT ROW[0], which reduces my program's readability. > > > > Can I access to row's contents by column name? > > > > Any help would be appreciated, > > Alan From larry.bates at websafe.com Thu Jun 1 16:03:46 2006 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 01 Jun 2006 09:03:46 -0500 Subject: Best way to do data source abstraction In-Reply-To: References: Message-ID: <447EF3C2.9060804@websafe.com> Arthur Pemberton wrote: > What is the best way to do data source abtraction? For example have > different classes with the same interface, but different > implementations. > > I was thinking of almost having classA as my main class, and have > classA dynamically "absorb" classFood into to based on the extension > of the input file received by classA. But this doesn't seem possible. > > Please advise. > > Thank you. > The best method I've found is to have a class that abstracts the data and presents the values from the data source via class attributes. If you also implement it as an iterator (e.g. give it __iter__ and __next__ methods), you can easily iterate over the resultset from each data source. With this method I've abstracted data in CSV files, fixed ASCII files, SQL tables, Excel Spreadsheets, tab delimited files that are members of a .ZIP archive, you name it. Short example (not tested): class foo: ''' Class to abstract tab delimited files ''' def __init__(self, filepath, columnnames): self.fp=open(filepath, 'r') self.columnnames=columnnames return def __iter__(self): return self def next(self): # # Try to get the next line from file # try: line=self.fp.next() except StopIteration: self.fp.close() raise # # Decode the tab delimited line into its parts # line=line.rstrip() if not line: raise StopIteration values=line.split('\t') print "values=", values l=zip(self.columnnames, values) print l for column, value in l: setattr(self, column, value) return if __name__ == "__main__": obj=foo('abc.txt', ['name', 'address1', 'address2', 'city', 'state', 'zip']) for entry in obj: print "" print "Name........", obj.name print "Address1....", obj.address1 print "Address2....", obj.address2 print "City........", obj.city print "State.......", obj.state print "Zip.........", obj.zip -Larry Bates From daniel.dittmar at sap.corp Thu Jun 1 15:54:00 2006 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Thu, 01 Jun 2006 15:54:00 +0200 Subject: DB-API: how can I find the column names in a cursor? In-Reply-To: References: Message-ID: A.M wrote: > for row in out_cur: > > print row > [...] > > The other problem is accessing data in each row by column name. One useful technique is for col1, col2, col3 in out_cur: sum = sum + col3 Access is still by index, but your code uses ordinary Python variables. It works better with SELECTs as you can choose the output columns in the SQL. With stored procedures, there's always the possibility of someone changing the structure of the result set. There exists a general library for your solution: http://opensource.theopalgroup.com/ Daniel From johnjsal at NOSPAMgmail.com Thu Jun 1 16:01:36 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 01 Jun 2006 14:01:36 GMT Subject: creating a new database with mysqldb In-Reply-To: References: Message-ID: <4rCfg.2206$No6.47203@news.tufts.edu> Frithiof Andreas Jensen wrote: > "John Salerno" wrote in message > news:gcKag.2113$No6.46302 at news.tufts.edu... >> Since the connect method of mysqldb requires a database name, it > seems >> like you can't use it without having a database already created. > > The web hotel I use create *one* database together with the account. > > I.O.W: > > I cannot create any databases; I can create/delete as many tables as I > like within the database (up to the disk space that I have). This is > pretty normal, I think. > > No, I can create 25 databases. From larry.bates at websafe.com Thu Jun 1 16:03:46 2006 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 01 Jun 2006 09:03:46 -0500 Subject: Best way to do data source abstraction In-Reply-To: References: Message-ID: <447EF3C2.9060804@websafe.com> Arthur Pemberton wrote: > What is the best way to do data source abtraction? For example have > different classes with the same interface, but different > implementations. > > I was thinking of almost having classA as my main class, and have > classA dynamically "absorb" classFood into to based on the extension > of the input file received by classA. But this doesn't seem possible. > > Please advise. > > Thank you. > The best method I've found is to have a class that abstracts the data and presents the values from the data source via class attributes. If you also implement it as an iterator (e.g. give it __iter__ and __next__ methods), you can easily iterate over the resultset from each data source. With this method I've abstracted data in CSV files, fixed ASCII files, SQL tables, Excel Spreadsheets, tab delimited files that are members of a .ZIP archive, you name it. Short example (not tested): class foo: ''' Class to abstract tab delimited files ''' def __init__(self, filepath, columnnames): self.fp=open(filepath, 'r') self.columnnames=columnnames return def __iter__(self): return self def next(self): # # Try to get the next line from file # try: line=self.fp.next() except StopIteration: self.fp.close() raise # # Decode the tab delimited line into its parts # line=line.rstrip() if not line: raise StopIteration values=line.split('\t') print "values=", values l=zip(self.columnnames, values) print l for column, value in l: setattr(self, column, value) return if __name__ == "__main__": obj=foo('abc.txt', ['name', 'address1', 'address2', 'city', 'state', 'zip']) for entry in obj: print "" print "Name........", obj.name print "Address1....", obj.address1 print "Address2....", obj.address2 print "City........", obj.city print "State.......", obj.state print "Zip.........", obj.zip -Larry Bates From aisaac0 at verizon.net Thu Jun 1 16:07:15 2006 From: aisaac0 at verizon.net (David Isaac) Date: Thu, 01 Jun 2006 14:07:15 GMT Subject: argmax Message-ID: 1. Why is there no argmax built-in? (This would return the index of the largest element in a sequence.) 2. Is this a good argmax (as long as I know the iterable is finite)? def argmax(iterable): return max(izip( iterable, count() ))[1] 3. If this is the only place in a module where I need count and izip, should I import them at the module level or at the level of the function? What are the considerations here? Thanks, Alan Isaac From aleax at mac.com Thu Jun 1 16:24:24 2006 From: aleax at mac.com (Alex Martelli) Date: Thu, 1 Jun 2006 07:24:24 -0700 Subject: shuffling elements of a list References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> <1149147164.012044.66960@u72g2000cwu.googlegroups.com> Message-ID: <1hg8scu.94jp741hydj6dN%aleax@mac.com> Peter Otten <__peter__ at web.de> wrote: > Gerard Flanagan wrote: > > Ben Finney wrote: > > >> pile_index = 0 > >> for card in deck: > >> piles[pile_index].append(card) > >> pile_index = (pile_index + 1) % numpiles > > > > no need to maintain an index ;-) > > > > piles = [ list() for _ in range(n) ] > > for i, card in enumerate(deck): > > piles[i % numpiles].append(card) > > No need to maintain an index ;-) > > piles = [deck[start::numpiles] for start in range(numpiles)] > > Assuming deck is a list, that is. Or, for deck hypothetically being an arbitrary iterable, import itertools as it piles = [ list() for _ in range(numpiles) ] for pile, card in it.izip(it.cycle(piles), deck): pile.append(card) i.e., let itertools do the cycling for you. But, sure, for this problem one can no doubt assume that deck is sliceable, and extended slicing (==slicing with a stride) comes in handy. Alex From michele.petrazzo at TOGLIunipex.it Thu Jun 1 16:27:11 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Thu, 01 Jun 2006 14:27:11 GMT Subject: Trying to get FreeImagePy to work. In-Reply-To: <1149166096.176405.22780@i40g2000cwc.googlegroups.com> References: <1148651668.578852.3160@i40g2000cwc.googlegroups.com> <7fEdg.13375$cX1.201311@twister2.libero.it> <1148655611.990937.322350@j73g2000cwa.googlegroups.com> <1149166096.176405.22780@i40g2000cwc.googlegroups.com> Message-ID: <3PCfg.20835$cX1.315781@twister2.libero.it> Iain King wrote: > Michele Petrazzo wrote: >> Iain King wrote: >>> Michele Petrazzo wrote: >>> >>> I downloaded and installed 0.9.9.3, and it now works. Thanks! >>> >> I advice you to don't use that ctypes version... Better is to use >> the newest one and update freeimagepy! >> >>> Iain >>> >> Michele > > OK, Ive installed the latest versions I can find, which are > FreeImagePy 1.2.4 and ctypes 0.9.9.6, and I'm back to the error I had > earlier. Do you know what's wrong? > > Iain > Can you download the last svn version from sf.net? Otherwise I'll send you the last sources privately. Bye, Michele From duncanm255 at hotmail.com Thu Jun 1 16:34:23 2006 From: duncanm255 at hotmail.com (D) Date: 1 Jun 2006 07:34:23 -0700 Subject: Starting New Process Message-ID: <1149172463.881528.131290@j55g2000cwa.googlegroups.com> Hello, I need to write a server program that performs the following tasks: 1) Listens on TCP port 5555 for a connection 2) When client connects, launches application (for example, vi), then closes connection with client 3) Goes back to listening on TCP port 5555 for an incoming connection The main thing I need to make sure of is that when the server program closes, that the applications that were launched remain running (i.e. I would need to launch them independently of the server program). Any help as to how to do this would be greatly appreciated! From aljosa.mohorovic at gmail.com Thu Jun 1 16:52:20 2006 From: aljosa.mohorovic at gmail.com (aljosa) Date: 1 Jun 2006 07:52:20 -0700 Subject: image lib & Qt4 Message-ID: <1149173540.470829.34940@c74g2000cwc.googlegroups.com> i'm looking for image lib which supports common image types (maybe freeimagepy?) and is relatively easy to display image loaded through that lib in PyQt4. any ideas? Aljosa From alanalan at newsgroup.nospam Thu Jun 1 16:42:40 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 1 Jun 2006 10:42:40 -0400 Subject: New to Python: Do we have the concept of Hash in Python? Message-ID: Hi, I am new to Python, with C#/Java background Is there any built-in Hash implementation in Python? I am looking for a container that I can access to it's items by name. Something like this: Print container["memeberName"] I am asking this because I learned that DB-API in Python doesn't offer access to cursor columns by name. The only option is access by index. I hope that I've got it wrong! I learned Ruby perfectly supports that. Thank you, Alan From dndfan at hotpop.com Thu Jun 1 16:58:40 2006 From: dndfan at hotpop.com (The Prophet) Date: 1 Jun 2006 07:58:40 -0700 Subject: os.walk trouble Message-ID: <1149173920.903876.68370@c74g2000cwc.googlegroups.com> As my first Python script, I am trying to make a program that recurses a directory searching for files whose names match a pattern. I have a basic idea of what the regexp would look like (and I can get more information about that), but I am stuck with incorrect understanding of os.walk. I've tried: root, dirs, files = os.walk(dirname) but it fails for some reason. I have seen this done before in the tutorial (I think it's called sequence unpacking). What is the proper way to do this? Thanks in advance. From saint.infidel at gmail.com Thu Jun 1 17:01:06 2006 From: saint.infidel at gmail.com (infidel) Date: 1 Jun 2006 08:01:06 -0700 Subject: New to Python: Do we have the concept of Hash in Python? In-Reply-To: References: Message-ID: <1149174066.510963.83060@c74g2000cwc.googlegroups.com> > Is there any built-in Hash implementation in Python? I am looking for a > container that I can access to it's items by name. Something like this: > > Print container["memeberName"] You obviously haven't read the tutorial, they're called "dictionaries" in Python > I am asking this because I learned that DB-API in Python doesn't offer > access to cursor columns by name. The only option is access by index. I hope > that I've got it wrong! That's because the DB-API uses tuples to represent records. > I learned Ruby perfectly supports that. Yay for Ruby. From michael.f.ellis at gmail.com Thu Jun 1 17:02:21 2006 From: michael.f.ellis at gmail.com (michael.f.ellis at gmail.com) Date: 1 Jun 2006 08:02:21 -0700 Subject: An oddity in list comparison and element assignment Message-ID: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> The following script puzzles me. It creates two nested lists that compare identically. After identical element assignments, the lists are different. In one case, a single element is replaced. In the other, an entire column is replaced. --------------------------------------------------------------------------------------- ''' An oddity in the behavior of lists of lists. Occurs under Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32. Not tested on other platforms or builds. ''' a =[[[1,2],[1,2]],[[1,2],[1,2]]] b = [[range(1,3)]*2]*2 assert(a==b) print "Initially, python reports that the lists are equal" a[1][1]=[5] b[1][1]=[5] try: assert(a==b) except AssertionError: print "After identical element assignments, the lists are not equal" print "a is now ", a print "b is now ", b ------------------------------------------------------------------------------------- Here's the output on my system. ------------------------------------------------------------------------------------ Initially, python reports that the lists are equal After identical element assignments, the lists are not equal a is now [[[1, 2], [1, 2]], [[1, 2], [5]]] b is now [[[1, 2], [5]], [[1, 2], [5]]] ------------------------------------------------------------------------------------ This seems contrary to one of my fundamental expectations, namely that objects which compare equally must remain equal after identical operations. I think what must be going on is that the 'b' list contains replicated references instead of copies of [range(1,3)]*2 . IMO, python's == operator should detect this difference in list structure since it leads to different behavior under element assignments. Mike Ellis From elekis at gmail.com Thu Jun 1 17:03:16 2006 From: elekis at gmail.com (elekis) Date: 1 Jun 2006 08:03:16 -0700 Subject: how to create a cgi folder??? Message-ID: <1149174196.582085.5150@y43g2000cwc.googlegroups.com> hi there I have a host who suport python cgi script (www.frihost.com that's cool) and discovert python (and mysql) I would like to make my own site on python . But I woulud like to try before on my own machine (localhost.) So I would like to know how to create a CGI folder ??? I installed apache (I m under Ubuntu-linux) php and mysql cause in a first time it was that I used. but... is ther a package or a binary who do all ??? thanks a++++ From exarkun at divmod.com Thu Jun 1 17:09:14 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 1 Jun 2006 11:09:14 -0400 Subject: Starting New Process In-Reply-To: <1149172463.881528.131290@j55g2000cwa.googlegroups.com> Message-ID: <20060601150914.28682.2078896178.divmod.quotient.9318@ohm> On 1 Jun 2006 07:34:23 -0700, D wrote: >Hello, I need to write a server program that performs the following >tasks: > >1) Listens on TCP port 5555 for a connection >2) When client connects, launches application (for example, vi), then >closes connection with client >3) Goes back to listening on TCP port 5555 for an incoming connection Untested: from twisted.internet import protocol, reactor class ViRunner(protocol.Protocol): def connectionMade(self): reactor.spawnProcess( None, '/usr/bin/setsid', ['setsid', '/usr/bin/vi']) self.transport.loseConnection() f = protocol.ServerFactory() f.protocol = ViRunner reactor.listenTCP(5555, f) reactor.run() Jean-Paul From brian at sweetapp.com Thu Jun 1 17:10:14 2006 From: brian at sweetapp.com (Brian Quinlan) Date: Thu, 01 Jun 2006 17:10:14 +0200 Subject: New to Python: Do we have the concept of Hash in Python? In-Reply-To: References: Message-ID: <447F0356.3090207@sweetapp.com> A.M wrote: > Is there any built-in Hash implementation in Python? I am looking for a > container that I can access to it's items by name. Something like this: > > Print container["memeberName"] d = {"memberName" : "some value"} print d["memberName"] > I am asking this because I learned that DB-API in Python doesn't offer > access to cursor columns by name. The only option is access by index. I hope > that I've got it wrong! > > I learned Ruby perfectly supports that. Python does not use column names by default because they are not portable across database implementations. That being said, you can get them easily, if you want. Look at the "description" attribute of your cursor instance. Cheers, Brian From aleax at mac.com Thu Jun 1 17:15:21 2006 From: aleax at mac.com (Alex Martelli) Date: Thu, 1 Jun 2006 08:15:21 -0700 Subject: An oddity in list comparison and element assignment References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> Message-ID: <1hg8ug8.m01zhwehpk66N%aleax@mac.com> wrote: ... > operations. I think what must be going on is that the 'b' list > contains replicated references instead of copies of [range(1,3)]*2 . Right. > IMO, python's == operator should detect this difference in list > structure since it leads to different behavior under element > assignments. Wrong; equality does not imply any check on identity. You can consider the definition of "list A equals list B" as: -- len(A) == len(B), AND, -- for each valid index i, A[i] == B[i] This is an extremely natural definition of "equality" for containers: "they have EQUAL items" [[in the same order, for containers for which order is relevant]]. Nowhere in this extremely natural definition does the IDENTITY of the items come into play. Therefore, your expectations about the effects of item alterations (for alterable items) are ill-founded. Try concisely expressing your "should" -- constructively, as pseudocode that one could use to check for your "strengthened equality", not in abstract terms of constraints -- and if (as I strongly suspect) you cannot find a definition that is as simple, concise and natural as the two-liner above, this might help convince you that your desired definition would NOT be the most obvious, natural and fundamental, and therefore would not be appropriate to pick as part of the language's core. Indeed, it's an interesting problem to code up, if one wants any generality (for example, identity of immutable items _whose items or attributes are in turn immutable_ probably should not matter even for your "strengthened" equality... but that's pretty hard to express!-). Alex From iainking at gmail.com Thu Jun 1 17:15:38 2006 From: iainking at gmail.com (Iain King) Date: 1 Jun 2006 08:15:38 -0700 Subject: Trying to get FreeImagePy to work. In-Reply-To: <3PCfg.20835$cX1.315781@twister2.libero.it> References: <1148651668.578852.3160@i40g2000cwc.googlegroups.com> <7fEdg.13375$cX1.201311@twister2.libero.it> <1148655611.990937.322350@j73g2000cwa.googlegroups.com> <1149166096.176405.22780@i40g2000cwc.googlegroups.com> <3PCfg.20835$cX1.315781@twister2.libero.it> Message-ID: <1149174938.337973.85950@g10g2000cwb.googlegroups.com> Michele Petrazzo wrote: > Iain King wrote: > > Michele Petrazzo wrote: > >> Iain King wrote: > >>> Michele Petrazzo wrote: > >>> > >>> I downloaded and installed 0.9.9.3, and it now works. Thanks! > >>> > >> I advice you to don't use that ctypes version... Better is to use > >> the newest one and update freeimagepy! > >> > >>> Iain > >>> > >> Michele > > > > OK, Ive installed the latest versions I can find, which are > > FreeImagePy 1.2.4 and ctypes 0.9.9.6, and I'm back to the error I had > > earlier. Do you know what's wrong? > > > > Iain > > > > Can you download the last svn version from sf.net? Otherwise I'll send > you the last sources privately. > > Bye, > Michele Sorry, I hadn't heard of SVN before, so I didn't know what you were talking about earlier :). I got the TortoiseSVN client though, and checked out your newest build, copied it over the top of site-packages/freeimagepy, updated my ctypes back to 0.9.9.6 (I'd regressed again), ran my program, and it worked. Thanks! Next question (and what I'm using FreeImagePy for): I'm loading a pile of TIF's as thumbnails into a wx list control. I load the image with FIPY, convert it to PIL, use PIL's antialiasing thumbnail function, then load it from there into wx. However, when I'm do the fipy.convertToPil(), it inverts the image? I've inserted a fipy.invert() before the conversion as a temporary fix, but is there a reason for this? relevant code: def getHeaders(files): thumbs = [] for f in files: print "Adding %s" % f fi = FIPY.Image(f) fi.setCurrentPage(0) fi.invert() #temp fix thumb = fi.convertToPil() thumb.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS) thumbs.append((os.path.basename(f), pilToBitmap(thumb))) thumbs.sort() return thumbs Iain p.s. thanks again From python.list at tim.thechases.com Thu Jun 1 17:27:21 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 01 Jun 2006 10:27:21 -0500 Subject: os.walk trouble In-Reply-To: <1149173920.903876.68370@c74g2000cwc.googlegroups.com> References: <1149173920.903876.68370@c74g2000cwc.googlegroups.com> Message-ID: <447F0759.1030300@tim.thechases.com> > but I am stuck with incorrect understanding of > os.walk. I've tried: > > root, dirs, files = os.walk(dirname) os.walk returns an iteratable sequence of those tuples. Thus, you want to have for filepath, dirs, files in os.walk(dirname): #you're looking at the "dirs" and "files" in filepath print "Currently in %s" % filepath print "\t[Directories in %s]" % filepath print "\n\t".join(dirs) print "\t[Files in %s]" % filepath print "\n\t".join(files) print "=" * 50 HTH, -tkc From siona at chiark.greenend.org.uk Thu Jun 1 17:16:51 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 01 Jun 2006 16:16:51 +0100 (BST) Subject: DB-API: how can I find the column names in a cursor? References: Message-ID: A.M wrote: >The other problem is accessing data in each row by column name. In Ruby I >can say: > >Print row["ColName"] > >In Python; however, I must access to row contents by integer index, like >PRINT ROW[0], which reduces my program's readability. > >Can I access to row's contents by column name? columns = dict((name, col) for col, name in enumerate(cursor.description)) print row[columns["ColName"]] And please don't top-post. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From duncan.booth at invalid.invalid Thu Jun 1 17:29:21 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 Jun 2006 15:29:21 GMT Subject: argmax References: Message-ID: David Isaac wrote: > 1. Why is there no argmax built-in? > (This would return the index of the largest element in a sequence.) Probably there isn't a built-in because it isn't a commonly needed function. What is your use-case for argmax? If for example you want to repeatedly remove the largest element from a list, then sort the list and pop the last element (or use a heap, except heapq lets you pop the smallest so you can't use it directly). From maxerickson at gmail.com Thu Jun 1 17:29:46 2006 From: maxerickson at gmail.com (Max Erickson) Date: Thu, 1 Jun 2006 15:29:46 +0000 (UTC) Subject: argmax References: Message-ID: "David Isaac" wrote: > 1. Why is there no argmax built-in? > (This would return the index of the largest element in a > sequence.) > > 2. Is this a good argmax (as long as I know the iterable is > finite)? def argmax(iterable): return max(izip( iterable, count() > ))[1] > use len: len(iterable)-1 max From jeffrey at fro.man Thu Jun 1 17:34:35 2006 From: jeffrey at fro.man (Jeffrey Froman) Date: Thu, 01 Jun 2006 08:34:35 -0700 Subject: New to Python: Do we have the concept of Hash in Python? References: Message-ID: <127u27pjm8gu1c1@corp.supernews.com> A.M wrote: > I am asking this because I learned that DB-API in Python doesn't offer > access to cursor columns by name. The only option is access by index. I > hope that I've got it wrong! While it's not part of the DB-API as far as I know, the MySQLdb package (and perhaps other DB access modules as well, I don't know) provides a "DictCursor" class that returns query results as a tuple of column-keyed dictionaries (hashes, already demonstrated by Brian). Jeffrey From george.sakkis at gmail.com Thu Jun 1 17:40:23 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 1 Jun 2006 08:40:23 -0700 Subject: argmax References: Message-ID: <1149176423.854154.152240@i39g2000cwa.googlegroups.com> David Isaac wrote: > 1. Why is there no argmax built-in? > (This would return the index of the largest element in a sequence.) I guess because it's not used frequently enough. I've needed argmax/argmin more than once though, so I would welcome them as builtins. > 2. Is this a good argmax (as long as I know the iterable is finite)? > def argmax(iterable): return max(izip( iterable, count() ))[1] Yes, it's ok. Here's another one that doesn't require importing itertools: def argmax(iterable): return max((x,i) for i,x in enumerate(iterable))[1] > 3. If this is the only place in a module where I need count and izip, > should I import them at the module level or at the level of the function? > What are the considerations here? Both have their merits. I like having the imports close to the point they're used, at least if used only once; OTOH having all imports at the top of the module makes easier to see the module's dependencies without grep'ing for import (that's especially useful for non-standard imported modules or new additions ot the std lib if backwards compatibility is an issue). George From alf at merlin.fayauffre.org Thu Jun 1 17:50:55 2006 From: alf at merlin.fayauffre.org (Alexandre Fayolle) Date: Thu, 1 Jun 2006 15:50:55 +0000 (UTC) Subject: argmax References: Message-ID: Le 01-06-2006, David nous disait: > 1. Why is there no argmax built-in? > (This would return the index of the largest element in a sequence.) You'll get argmin and argmax in Numeric and its descendants (numarray and numpy). -- Alexandre Fayolle LOGILAB, Paris (France) Formations Python, Zope, Plone, Debian: http://www.logilab.fr/formations D?veloppement logiciel sur mesure: http://www.logilab.fr/services Python et calcul scientifique: http://www.logilab.fr/science From eric_brunel at despammed.com Thu Jun 1 17:56:03 2006 From: eric_brunel at despammed.com (Eric Brunel) Date: Thu, 01 Jun 2006 17:56:03 +0200 Subject: Function mistaken for a method References: <447ee701$0$22029$626a54ce@news.free.fr> Message-ID: On Thu, 01 Jun 2006 15:07:26 +0200, bruno at modulix wrote: > Do yourself a favour : use new-style classes. > class C(object) I would if I could: I'm stuck with Python 2.1 for the moment (I should have mentionned it; sorry for that). [snip] >> Basically, I want an optional variant function across sub-classes of >> the same class. >> >> I did it like in C1 for a start, then I needed >> something like C2. The result is... surprising: >> >> 0 >> Traceback (most recent call last): >> File "func-vs-meth.py", line 18, in ? >> o2 = C2() >> File "func-vs-meth.py", line 5, in __init__ >> self.x = self.f(0) >> TypeError: () takes exactly 1 argument (2 given) > > Not surprising at all. > > Functions implement the descriptor protocol[1]. When bound to a class > and looked up via an instance, it's the __get__ method of the function > object that get called - with the instance as param, as defined by the > descriptor protocol. This method then return the function wrapped - with > the instance - in an Method object - which itself, when called, returns > the result of calling the function *with the instance as first > parameter*. Which is how methods can work on the instance, and why one > has to explicitly declare the instance parameter in "functions to be > used as methods", but not explicitly pass it at call time. > > (please some guru correct me if I missed something here, but AFAIK it > must be a correct enough description of method invocation mechanism in > Python). > > [1] about descriptors, see: > http://docs.python.org/ref/descriptors.html > http://www.geocities.com/foetsch/python/new_style_classes.htm#descriptors > >> So the first works and o1.x is actually 0. > > int is not a function. >>>> type(int) > > > int is a type. Python 2.1 again: >>> type(int) But as someone mentionned, the problem is the same with other built-in functions, such as chr, even in the latest Python version. I still find that a little counter-intuitive to have different behaviours for a built-in function and a Python function. I really would expect them to work (or not to work) the same in all situations, even if I now understand better how all works behind the scenes. But I'll live with it... [snip] > If you understood all my explanations, you now know how to solve the > problem. > > Else, here the solution: > > class C3(C): > f = lambda self, x: return x This is actually the first thing I did, but it seemed a bit weird to me to have a - let's say - callable with one parameter in one case and another with two parameters in the other one. So I finally turned my callable attribute into a real instance method, just for consistency. Anyway, thanks a lot for your explanations. -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From michael.f.ellis at gmail.com Thu Jun 1 18:00:18 2006 From: michael.f.ellis at gmail.com (michael.f.ellis at gmail.com) Date: 1 Jun 2006 09:00:18 -0700 Subject: An oddity in list comparison and element assignment References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> Message-ID: <1149177617.985251.74560@c74g2000cwc.googlegroups.com> Hi Alex, With all due respect to your well-deserved standing in the Python community, I'm not convinced that equality shouldn't imply invariance under identical operations. Perhaps the most fundamental notion is mathematics is that the left and right sides of an equation remain identical after any operation applied to both sides. Our experience of the physical world is similar. If I make identical modifications to the engines of two identical automobiles, I expect the difference in performance to be identical. If my expectation is met, I would assert that either the two vehicles were not identical to begin with or that my modifications were not performed identically. As to containers, would you say that envelope containing five $100 bills is the same as an envelope containing a single $100 bill and 4 xerox copies of it? If so, I'd like to engage in some envelope exchanges with you :-) As I see it, reference copying is a very useful performance and memory optimization. But I don't think it should undermine the validity of assert(a==b) as a predictor of invariance under identical operations. Cheers, Mike Ellis Alex Martelli wrote: > wrote: > Wrong; equality does not imply any check on identity. You can consider > the definition of "list A equals list B" as: > > -- len(A) == len(B), AND, > -- for each valid index i, A[i] == B[i] > > This is an extremely natural definition of "equality" for containers: > "they have EQUAL items" [[in the same order, for containers for which > order is relevant]]. Nowhere in this extremely natural definition does > the IDENTITY of the items come into play. From deets at nospam.web.de Thu Jun 1 18:01:24 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 01 Jun 2006 18:01:24 +0200 Subject: image lib & Qt4 References: <1149173540.470829.34940@c74g2000cwc.googlegroups.com> Message-ID: <4e8haiF1dp2heU1@uni-berlin.de> aljosa wrote: > i'm looking for image lib which supports common image types (maybe > freeimagepy?) and is relatively easy to display image loaded through > that lib in PyQt4. > any ideas? Use PIL & StringIO to create a in-memory representation of the image as e.g. PNG. Load that using Qt. Diez From __peter__ at web.de Thu Jun 1 18:03:47 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Jun 2006 18:03:47 +0200 Subject: argmax References: Message-ID: David Isaac wrote: > 2. Is this a good argmax (as long as I know the iterable is finite)? > def argmax(iterable): return max(izip( iterable, count() ))[1] There's a subtle difference to the builtin: argmax() gives you the (index of the) last maximum while max() returns the (value of the) first maximum: >>> from itertools import count, izip >>> def argmax(iterable): ... return max(izip(iterable, count()))[1] ... >>> class Int(int): pass ... >>> type(max([Int(0), 0])) # must be the first item then >>> argmax([Int(0), 0]) 1 If you care, here's the fix building on George's implementation: >>> def argmax2(iterable): ... return -max((v, -i) for i, v in enumerate(iterable))[1] ... >>> argmax2([Int(0), 0]) 0 Peter From 3dbernard at gmail.com Thu Jun 1 18:07:00 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 1 Jun 2006 12:07:00 -0400 Subject: Tkinter: select multiple entries in Listbox widget? Message-ID: <61d0e2b40606010907v4846da5dt39ab4f5f58293069@mail.gmail.com> Hello, Is there an option or a way to allow the selection of multiple entries in the Listbox widget? I could not find any, and would like to allow the end user to select multiple entries. Thanks Bernard From michael.f.ellis at gmail.com Thu Jun 1 18:05:04 2006 From: michael.f.ellis at gmail.com (michael.f.ellis at gmail.com) Date: 1 Jun 2006 09:05:04 -0700 Subject: An oddity in list comparison and element assignment In-Reply-To: <1149177617.985251.74560@c74g2000cwc.googlegroups.com> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> Message-ID: <1149177904.203543.285010@i39g2000cwa.googlegroups.com> oops! last sentence of 2nd paragraph in previous message should read "If my expectation is NOT met ..." From fredrik at pythonware.com Thu Jun 1 18:09:32 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 1 Jun 2006 18:09:32 +0200 Subject: New to Python: Do we have the concept of Hash in Python? References: Message-ID: "A.M" wrote: > I am new to Python, with C#/Java background that's not really much of an excuse for not reading *any* Python tutorial before you jump in... > I am asking this because I learned that DB-API in Python doesn't offer access to cursor columns by > name. The only option is access by index. I hope that I've got it wrong! several people have already told you how to deal with this in Python. please see the followups to your earlier post. > I learned Ruby perfectly supports that. Ruby's DB interface, perhaps. Python's standard DB-API doesn't support this by default, for portability and performance reasons. that doesn't mean that Python don't have "hashes", just that the DB-API doesn't provide dictionary-style access to columns. see the followups to your earlier post for more details, and ways to handle this. (a much better way to deal with this is of course to *name* the variables in your select statements, so 1) the database engine can spot errors early on, and 2) it won't have to fetch data that you don't really need). From d.schulz81 at gmx.net Thu Jun 1 18:10:09 2006 From: d.schulz81 at gmx.net (d.schulz81 at gmx.net) Date: 1 Jun 2006 09:10:09 -0700 Subject: Zope / Plone Groups Message-ID: <1149178209.825191.128050@c74g2000cwc.googlegroups.com> Hi, are there any specific groups for zope / plone regarding questions? my question is: How is it possible to use Zope 3 Products with Plone, which is an extension based on Zope 2? Thank you Dennis From python.list at tim.thechases.com Thu Jun 1 18:23:09 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 01 Jun 2006 11:23:09 -0500 Subject: An oddity in list comparison and element assignment In-Reply-To: <1149177617.985251.74560@c74g2000cwc.googlegroups.com> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> Message-ID: <447F146D.9070903@tim.thechases.com> > As to containers, would you say that envelope containing five $100 > bills is the same as an envelope containing a single $100 bill and 4 > xerox copies of it? If so, I'd like to engage in some envelope > exchanges with you :-) if len(set([bill.serialnumber for bill in envelope])) != len(envelope): refuseMichaelsExchange() Though the way references work, you would have an envelope containing only 5 slips of paper that all say "I have a $100 bill"... :) -tkc From skip at pobox.com Thu Jun 1 18:22:05 2006 From: skip at pobox.com (skip at pobox.com) Date: Thu, 1 Jun 2006 11:22:05 -0500 Subject: DB-API: how can I find the column names in a cursor? In-Reply-To: References: Message-ID: <17535.5165.592323.404609@montanaro.dyndns.org> Alan> The other problem is accessing data in each row by column name. In Alan> Ruby I can say: Alan> Print row["ColName"] Alan> In Python; however, I must access to row contents by integer Alan> index, like PRINT ROW[0], which reduces my program's readability. Alan> Can I access to row's contents by column name? There are a couple things you can try. First, see if the adaptor for your database has a way to specify that query results should be returned as a list of dicts instead of a list of tuples. MySQLdb allows you to select the style of cursor class to instantiate when you create the connection. I think Psycopg provides a dictcursor() method on the connection (though I may be misremembering - it's been awhile). Other adaptors may provide similar functionality. Failing that, you can whip something up yourself using the description attribute to which Fredrik referred: for row in curs.fetchall(): row = dict(zip([d[0] for d in curs.description], row)) ... Skip From tim.peters at gmail.com Thu Jun 1 18:23:07 2006 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 1 Jun 2006 12:23:07 -0400 Subject: An oddity in list comparison and element assignment In-Reply-To: <1149177617.985251.74560@c74g2000cwc.googlegroups.com> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> Message-ID: <1f7befae0606010923o5f870b80x70f1a9d95e589cf6@mail.gmail.com> [michael.f.ellis at gmail.com] > ... > As I see it, reference copying is a very useful performance and memory > optimization. But I don't think it should undermine the validity of > assert(a==b) as a predictor of invariance under identical operations. So, as Alex said last time, Try concisely expressing your "should" -- constructively, as pseudocode that one could use to check for your "strengthened equality", not in abstract terms of constraints -- and if (as I strongly suspect) you cannot find a definition that is as simple, concise and natural as the two-liner above, this might help convince you that your desired definition would NOT be the most obvious, natural and fundamental, and therefore would not be appropriate to pick as part of the language's core. Indeed, it's an interesting problem to code up, if one wants any generality (for example, identity of immutable items _whose items or attributes are in turn immutable_ probably should not matter even for your "strengthened" equality... but that's pretty hard to express!-). So try that. In reality, you can either learn to change your expectations, or avoid virtually all object-oriented programming languages. Object identity is generally fundamental to the intended semantics of such languages, not just an optimization. Think about a simpler case: a = [1] b = a assert(a == b) a.remove(1) b.remove(1) Oops. The last line dies with an exception, despite that a==b at the third statement and that ".remove(1)" is applied to both a and b. If you think a should not equal b at the third statement "because" of this, you're going to lead a life of increasing but needless despair ;-) From scott.daniels at acm.org Thu Jun 1 18:22:25 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 01 Jun 2006 09:22:25 -0700 Subject: TSV to HTML In-Reply-To: <1149157775.490474.173970@y43g2000cwc.googlegroups.com> References: <1149098823.979329.9220@f6g2000cwb.googlegroups.com> <447e268a$0$3699$4d3efbfe@news.sover.net> <1149126509.984331.306530@h76g2000cwa.googlegroups.com> <1149157775.490474.173970@y43g2000cwc.googlegroups.com> Message-ID: <447f0fdb$1@nntp0.pdx.net> Brian wrote: > One question (and this is a topic that I still have trouble getting my > arms around). Why is the text in STYLEBLOCK tripple quoted? Because triple-quoted strings can span lines and include single quotes and double quotes. -- --Scott David Daniels scott.daniels at acm.org From harlinseritt at yahoo.com Thu Jun 1 18:24:10 2006 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 1 Jun 2006 09:24:10 -0700 Subject: Finding web host headers Message-ID: <1149179050.315297.79470@j55g2000cwa.googlegroups.com> Is there any way to fetch a website's host/version headers using Python? Thanks, Harlin From fredrik at pythonware.com Thu Jun 1 18:25:32 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 1 Jun 2006 18:25:32 +0200 Subject: An oddity in list comparison and element assignment References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com><1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> Message-ID: michael.f.ellis at gmail.com wrote: > As to containers, would you say that envelope containing five $100 > bills is the same as an envelope containing a single $100 bill and 4 > xerox copies of it? If so, I'd like to engage in some envelope > exchanges with you :-) if you spent as much time *learning* stuff as you spend making up irrelevant examples, you might end up learning how assignments, repeat operators, and references work in Python. it's only hard to understand if you don't want to understand it. From aisaac0 at verizon.net Thu Jun 1 18:32:03 2006 From: aisaac0 at verizon.net (David Isaac) Date: Thu, 01 Jun 2006 16:32:03 GMT Subject: argmax References: Message-ID: <7EEfg.16123$lN5.4994@trnddc04> Thanks for all the replies. A couple of comments. 1. I think the usefulness of an argmax built-in can be assessed by looking at other languages (and e.g. at numpy). So I do not buy the "not needed" argument as presented. More like "haven't got around to it," I'm thinking. 2. The particular use case this time is strategy choice. The desired strategy (i.e., index) is the one with the highest payoff. 3. Thanks to George, and to Peter for noticing a subtle difference in the implementations. Alan Isaac From rpdooling at gmail.com Thu Jun 1 18:42:42 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 1 Jun 2006 09:42:42 -0700 Subject: os.walk trouble References: <1149173920.903876.68370@c74g2000cwc.googlegroups.com> Message-ID: <1149180162.128874.153330@i39g2000cwa.googlegroups.com> Neat. And looks better, at least on my machine, if you had a tab or two and an extra \n after the dirs. rick for filepath, dirs, files in os.walk(root): #you're looking at the "dirs" and "files" in filepath print "Currently in %s" % filepath print "\t[Directories in %s]" % filepath print '\t' + "\n\t".join(dirs) + '\n' print "\t[Files in %s]" % filepath print '\t' + "\n\t".join(files) print "=" * 50 From michele.petrazzo at TOGLIunipex.it Thu Jun 1 18:42:50 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Thu, 01 Jun 2006 16:42:50 GMT Subject: Trying to get FreeImagePy to work. In-Reply-To: <1149174938.337973.85950@g10g2000cwb.googlegroups.com> References: <1148651668.578852.3160@i40g2000cwc.googlegroups.com> <7fEdg.13375$cX1.201311@twister2.libero.it> <1148655611.990937.322350@j73g2000cwa.googlegroups.com> <1149166096.176405.22780@i40g2000cwc.googlegroups.com> <3PCfg.20835$cX1.315781@twister2.libero.it> <1149174938.337973.85950@g10g2000cwb.googlegroups.com> Message-ID: Iain King wrote: >> Can you download the last svn version from sf.net? Otherwise I'll send >> you the last sources privately. >> >> Bye, >> Michele > > I got the TortoiseSVN client though, and > checked out your newest build, copied it over the top of > site-packages/freeimagepy, updated my ctypes back to 0.9.9.6 (I'd > regressed again), ran my program, and it worked. Thanks! This is a good news! > Next question (and what I'm using FreeImagePy for): I'm loading a pile > of TIF's as thumbnails into a wx list control. I load the image with > FIPY, convert it to PIL, use PIL's antialiasing thumbnail function, > then load it from there into wx. Why use PIL for it and not FIPY directly? You can use the image.size or the other methods for resize the image > However, when I'm do the > fipy.convertToPil(), it inverts the image? No, it not invert the image... It only return the image as is. > I've inserted a > fipy.invert() before the conversion as a temporary fix, but is there a > reason for this? If you are have a min-is-white image (fax ?) that isn't the standard, you will have an "inverted" image, because PIl expect a min-is-black image! > relevant code: > > def getHeaders(files): > thumbs = [] > for f in files: > print "Adding %s" % f > fi = FIPY.Image(f) > fi.setCurrentPage(0) > fi.invert() #temp fix > thumb = fi.convertToPil() > thumb.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS) > thumbs.append((os.path.basename(f), pilToBitmap(thumb))) > thumbs.sort() > return thumbs Just a question, why "thumbs.sort" ? Inside this list you have only images! P.s. you can use also fi.currentPage = 0 rather then fi.setCurrentPage(0). Is think it look like better :) > > Iain > > p.s. thanks again > :) Michele From scott.daniels at acm.org Thu Jun 1 18:45:09 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 01 Jun 2006 09:45:09 -0700 Subject: An oddity in list comparison and element assignment In-Reply-To: <1149177617.985251.74560@c74g2000cwc.googlegroups.com> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> Message-ID: <447f152f@nntp0.pdx.net> michael.f.ellis at gmail.com wrote: > As to containers, would you say that envelope containing five $100 > bills is the same as an envelope containing a single $100 bill and 4 > xerox copies of it? If so, I'd like to engage in some envelope > exchanges with you :-) Would you say that envelope containing five $100 bills is equal to an envelope containing five $100 bills with different serial numbers? --Scott David Daniels scott.daniels at acm.org From scott.daniels at acm.org Thu Jun 1 18:46:43 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 01 Jun 2006 09:46:43 -0700 Subject: Zope / Plone Groups In-Reply-To: <1149178209.825191.128050@c74g2000cwc.googlegroups.com> References: <1149178209.825191.128050@c74g2000cwc.googlegroups.com> Message-ID: <447f158d$1@nntp0.pdx.net> d.schulz81 at gmx.net wrote: > are there any specific groups for zope / plone regarding questions? Check gmane (google for it). -- --Scott David Daniels scott.daniels at acm.org From alanalan at newsgroup.nospam Thu Jun 1 18:35:20 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 1 Jun 2006 12:35:20 -0400 Subject: Python for Visual Basic or C# programmers Message-ID: Hi, I am trying to find the equivalent functions such as vb's str or asc in Python. Is there any resource that help me to find these kinds of functions in Python faster? Thank you, Alan From aljosa.mohorovic at gmail.com Thu Jun 1 18:53:34 2006 From: aljosa.mohorovic at gmail.com (aljosa) Date: 1 Jun 2006 09:53:34 -0700 Subject: image lib & Qt4 In-Reply-To: <4e8haiF1dp2heU1@uni-berlin.de> References: <1149173540.470829.34940@c74g2000cwc.googlegroups.com> <4e8haiF1dp2heU1@uni-berlin.de> Message-ID: <1149180814.585713.209640@i39g2000cwa.googlegroups.com> does anybody know how to load (in-memory representation of PNG image) from Qt (v.4.1.3) as QImage? Diez B. Roggisch wrote: > aljosa wrote: > > > i'm looking for image lib which supports common image types (maybe > > freeimagepy?) and is relatively easy to display image loaded through > > that lib in PyQt4. > > any ideas? > > Use PIL & StringIO to create a in-memory representation of the image as e.g. > PNG. Load that using Qt. > > Diez From python.list at tim.thechases.com Thu Jun 1 19:08:27 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 01 Jun 2006 12:08:27 -0500 Subject: Finding web host headers In-Reply-To: <1149179050.315297.79470@j55g2000cwa.googlegroups.com> References: <1149179050.315297.79470@j55g2000cwa.googlegroups.com> Message-ID: <447F1F0B.6000600@tim.thechases.com> > Is there any way to fetch a website's host/version headers using > Python? >>> import httplib >>> conn = httplib.HTTPConnection("docs.python.org") >>> conn.connect() >>> conn.request("HEAD", "/") >>> response = dict([(k.lower(), v) for k,v in conn.getresponse()]) >>> conn.close() >>> server = response["server"] >>> print server Apache/2.0.54 (Debian GNU/Linux) DAV/2 SVN/1.1.4 mod_python/3.1.3 Python/2.3.5 mod_ssl/2.0.54 OpenSSL/0.9.7e I've found a bit of discrepancy with regards to the case of the "server" portion, so the above code just normalizes it to lowercase and then shoves it in a dictionary. You can then do as you please with the contents of the "server" variable. It's theoretically possible that the server can return differing headers based on the URL you request or its method. You'll have to adjust the request() call for the method (GET/HEAD/POST, etc) and for the resource you want (in this case, just "/") -tkc From alanalan at newsgroup.nospam Thu Jun 1 18:49:06 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 1 Jun 2006 12:49:06 -0400 Subject: New to Python: Do we have the concept of Hash in Python? References: Message-ID: "Fredrik Lundh" wrote in message news:mailman.6414.1149178232.27775.python-list at python.org... > "A.M" wrote: > >> I am new to Python, with C#/Java background > > that's not really much of an excuse for not reading *any* Python tutorial > before > you jump in... Hi Fredrik, 1st of all, I am really impressed by this Python community. Answers are helpful and I am having excellent progress. I appreciate everybody's help. This is my 1st day that I am seriously diving into Python and I have to finish this application by the end of today. Maybe it wasn't a good idea to choose the language that I don't know when I have to deliver my work in such short time. I understand that my question might seems very trivial to you, but please consider the fact that I am in time pressure and I cannot go through a 400 book today. I promises I'll do that this weekend ;) Wish luck for me! Thank you for your post, Alan From jes at nl.demon.net Thu Jun 1 19:13:24 2006 From: jes at nl.demon.net (Jim Segrave) Date: Thu, 01 Jun 2006 17:13:24 -0000 Subject: An oddity in list comparison and element assignment References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> Message-ID: <127u81kdf70ch8d@corp.supernews.com> In article <1149177617.985251.74560 at c74g2000cwc.googlegroups.com>, wrote: >Hi Alex, >With all due respect to your well-deserved standing in the Python >community, I'm not convinced that equality shouldn't imply invariance >under identical operations. > >Perhaps the most fundamental notion is mathematics is that the left and >right sides of an equation remain identical after any operation applied >to both sides. Our experience of the physical world is similar. If I >make identical modifications to the engines of two identical >automobiles, I expect the difference in performance to be identical. >If my expectation is met, I would assert that either the two vehicles >were not identical to begin with or that my modifications were not >performed identically. > >As to containers, would you say that envelope containing five $100 >bills is the same as an envelope containing a single $100 bill and 4 >xerox copies of it? If so, I'd like to engage in some envelope >exchanges with you :-) > >As I see it, reference copying is a very useful performance and memory >optimization. But I don't think it should undermine the validity of >assert(a==b) as a predictor of invariance under identical operations. I think you end up with a totally unwieldy definition of '==' for containers, since you have to check for _identical_ aliasing to whatever depth it might occur, and, if you insist on equality modeling the physical world, two lists can only be equal if: for each corresponding element in the two lists, either the element is a reference to the same underlying object or the corresponding elements are references to objects which do not have and never will have other references bound to them. For example: ra = ['a', 'a'] rb = ['b', 'b'] l1 = [ra, rb] l2 = [ra, rb] This will be equal by your definition and will preserve equality over identical operations on l1 and l2 l3 = [ ['a', 'b'], ['a', 'b']] This list will be identical, under your definition, so long as we don't have anyone doing anything to the references ra or rb. Your equality test has to claim that l1 and l3 are not equal, since ra could be changed and that's not an operation on l1 or l3 This also leaves out the complexity of analysiing nested structures - if you have a tuple, containing tuples which contain lists, then are those top level tuples 'equal' if there are aliases in the lists? How many levels deep should an equality test go? Does the more common test, to see if the elements of a sequence are identical at the time of comparision need a new operator or hand coding, since most of the time programmers aren't interested in future equality or not of the structures. -- Jim Segrave (jes at jes-2.demon.nl) From python.list at tim.thechases.com Thu Jun 1 19:20:44 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 01 Jun 2006 12:20:44 -0500 Subject: Finding web host headers In-Reply-To: <447F1F0B.6000600@tim.thechases.com> References: <1149179050.315297.79470@j55g2000cwa.googlegroups.com> <447F1F0B.6000600@tim.thechases.com> Message-ID: <447F21EC.40801@tim.thechases.com> >> Is there any way to fetch a website's host/version headers using >> Python? > > >>> import httplib > >>> conn = httplib.HTTPConnection("docs.python.org") > >>> conn.connect() > >>> conn.request("HEAD", "/") > >>> response = dict([(k.lower(), v) for k,v in conn.getresponse()]) > >>> conn.close() > >>> server = response["server"] > >>> print server > Apache/2.0.54 (Debian GNU/Linux) DAV/2 SVN/1.1.4 mod_python/3.1.3 > Python/2.3.5 mod_ssl/2.0.54 OpenSSL/0.9.7e Dang, I copied that over by hand and miscopied it with a big error or two. It can also be cleaned up a bit, as I learned (the getheader() call is case-insensitive, and the connect() call was superfluous). Copying verbatim... >>> import httplib >>> conn = httplib.HTTPConnection("docs.python.org") >>> conn.request("HEAD", "/") >>> response = conn.getresponse() >>> conn.close() >>> server = response.getheader("server") >>> print server Apache/2.0.54 (Debian GNU/Linux) DAV/2 SVN/1.1.4 mod_python/3.1.3 Python/2.3.5 mod_ssl/2.0.54 OpenSSL/0.9.7e Sorry about the rubbish code the first time out the gate. -tkc From greg.kujawa at gmail.com Thu Jun 1 19:17:45 2006 From: greg.kujawa at gmail.com (gregarican) Date: 1 Jun 2006 10:17:45 -0700 Subject: New to Python: Do we have the concept of Hash in Python? References: Message-ID: <1149182265.257263.159210@f6g2000cwb.googlegroups.com> Lemme see, starting *and* finishing a project in a language you've never practically used before within a day's time? Sounds like a clip from next season's opener of the TV show '24' to me. I came from using Ruby about a year or so and even then it took a couple of days of browsing through the Python docs and playing around until I could consider myself somewhat useful. Coming from Java and C# might make the departure a little steeper. Good luck! A.M wrote: > "Fredrik Lundh" wrote in message > news:mailman.6414.1149178232.27775.python-list at python.org... > > "A.M" wrote: > > > >> I am new to Python, with C#/Java background > > > > that's not really much of an excuse for not reading *any* Python tutorial > > before > > you jump in... > > Hi Fredrik, > > 1st of all, I am really impressed by this Python community. Answers are > helpful and I am having excellent progress. I appreciate everybody's help. > > > > This is my 1st day that I am seriously diving into Python and I have to > finish this application by the end of today. Maybe it wasn't a good idea to > choose the language that I don't know when I have to deliver my work in such > short time. I understand that my question might seems very trivial to you, > but please consider the fact that I am in time pressure and I cannot go > through a 400 book today. I promises I'll do that this weekend ;) Wish luck > for me! > > > > Thank you for your post, > > Alan From skip at pobox.com Thu Jun 1 19:28:43 2006 From: skip at pobox.com (skip at pobox.com) Date: Thu, 1 Jun 2006 12:28:43 -0500 Subject: New to Python: Do we have the concept of Hash in Python? In-Reply-To: References: Message-ID: <17535.9163.63334.44669@montanaro.dyndns.org> Alan> but please consider the fact that I am in time pressure and I Alan> cannot go through a 400 book today. The tutorial is online and not 400 pages long: http://www.python.org/doc/current/tut/tut.html It's got a pretty comprehensive table of contents, looking at which you might jump quickly to Chapter 5, "Data Structures", and quickly eliminate lists, sets and maybe tuples as possible synonyms for "hash" and investigate Section 5.5, "Dictionaries" more closely. The first sentence of that section should ring bells: Another useful data type built into Python is the dictionary. Dictionaries are sometimes found in other languages as ``associative memories'' or ``associative arrays''. I suspect that was what Fredrik was thinking you might reasonably have done before asking on the list. In addition, you could have probably answered your own question faster by using the online documentation instead of waiting for the Q&A round-trip to comp.lang.python. Skip From john at castleamber.com Thu Jun 1 19:41:33 2006 From: john at castleamber.com (John Bokma) Date: 1 Jun 2006 17:41:33 GMT Subject: how to print newline in xml? References: <1149023930.292203.152540@u72g2000cwu.googlegroups.com> <1149145466.190011.146250@i39g2000cwa.googlegroups.com> Message-ID: "anatoli.barski at googlemail.com" wrote: > Thank you for a possible solution, but it's not what I'm looking for, > cause something like would look quite similar... for > big elements like robot it would be ok to use comment as a child of > element - but imagine I'd like to comment transformation: > > I wouldn't like to make this > element parent of a description - it is not nice - I have lots of such > elements. Then add the comment to the parent of transformation, or an other option might be: > It is important that a user after having a glance at the document is > able to quickly find and change some values. I don't want to bother > him with reading documentation nodes - but if he needs - they should > be there... the only possible solution I can think of would be: > > > Several of your comments are stating the obvious, it's like: x++ increments the value x contains with one > '123' If you want to control the formatting to mimick vb or create different formatting you can use. " %d" % 123 --> ' 123' The format specifier is just like 'C's printf format strings. A tuple should follow the % sign if formatting more than 1 number. "%d %d" % (123, 456) Python has a similar function to vb's asc. It is ord(). ord() accepts a single character, whereas asc operates on the first character of a string. To mimick vb you could do s = 'hello' ord(s[0]) --> 104 I am unaware of any reference associating vb functionality with Python functionality. Then again, I never looked for one. From rpdooling at gmail.com Thu Jun 1 20:03:04 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 1 Jun 2006 11:03:04 -0700 Subject: os.walk trouble References: <1149173920.903876.68370@c74g2000cwc.googlegroups.com> Message-ID: <1149184984.891834.294470@y43g2000cwc.googlegroups.com> >> root, dirs, files = os.walk(dirname) If you want to do it this way, you need to stop it after the first one: root, dirs, files = os.walk(dirname).next() print root print dirs print files see this thread http://tinyurl.com/rmyo4 From duncanm255 at hotmail.com Thu Jun 1 20:08:04 2006 From: duncanm255 at hotmail.com (D) Date: 1 Jun 2006 11:08:04 -0700 Subject: Starting New Process In-Reply-To: References: <1149172463.881528.131290@j55g2000cwa.googlegroups.com> Message-ID: <1149185284.820789.321130@y43g2000cwc.googlegroups.com> Thanks, Jean-Paul - is there any way to do it without using Twisted, since I am not very familiar with it? (i.e. just using the os library) Thanks. Jean-Paul Calderone wrote: > On 1 Jun 2006 07:34:23 -0700, D wrote: > >Hello, I need to write a server program that performs the following > >tasks: > > > >1) Listens on TCP port 5555 for a connection > >2) When client connects, launches application (for example, vi), then > >closes connection with client > >3) Goes back to listening on TCP port 5555 for an incoming connection > > Untested: > > from twisted.internet import protocol, reactor > > class ViRunner(protocol.Protocol): > def connectionMade(self): > reactor.spawnProcess( > None, > '/usr/bin/setsid', > ['setsid', '/usr/bin/vi']) > self.transport.loseConnection() > > f = protocol.ServerFactory() > f.protocol = ViRunner > reactor.listenTCP(5555, f) > reactor.run() > > Jean-Paul From alanalan at newsgroup.nospam Thu Jun 1 20:00:42 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 1 Jun 2006 14:00:42 -0400 Subject: Member index in toples Message-ID: <_TFfg.2976$EF1.229574@news20.bellglobal.com> Hi, I have a tuple like this: T = ("One","Two","Three","Four") Is there any built-in way to find what is the index of "Two" withouot looping within the tuple? Is the same feature available for lists or dictionaries? Thank you, Alan From akameswaran at gmail.com Thu Jun 1 20:16:20 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 1 Jun 2006 11:16:20 -0700 Subject: ideas for programs? In-Reply-To: References: Message-ID: <1149185780.594711.37530@y43g2000cwc.googlegroups.com> James Stroud wrote: > A digest of the major points summarizing the consensus opinion: > > Thomas Bartkus wrote: > > Python is your tool to put your expertise on a computer. Skill with > Python, > > or any computer language for that matter, counts for little. > > And akameswaran at gmail.com wrote: > > As far as employment. I come from a java background, and that seems > > the only language I can pay the bills with:). Particularly in the US > > paid python jobs are hard to come by. > > James Hmm, I'm not clear what you were trying to say when you put these two quotes together. They seem actually opposed to each other. Despite what I wrote, Thomas is making a more accurate statement. However, Java EXPERIENCE does look good on my resume - and seems to carry a lot more weight than python experience. I don't like that fact - but let's face it, a lot of HR departments look at things just that way. From Serge.Orlov at gmail.com Thu Jun 1 20:18:46 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 1 Jun 2006 11:18:46 -0700 Subject: struct: type registration? In-Reply-To: References: <447e4b98$1@news.eftel.com> Message-ID: <1149185926.636174.48970@y43g2000cwc.googlegroups.com> Giovanni Bajo wrote: > John Machin wrote: > > I am an idiot, so please be gentle with me: I don't understand why you > > are using struct.pack at all: > > Because I want to be able to parse largest chunks of binary datas with custom > formatting. Did you miss the whole point of my message: > > struct.unpack("3liiSiiShh", data) Did you want to write struct.unpack("Sheesh", data) ? Seriously, the main problem of struct is that it uses ad-hoc abbreviations for relatively rarely[1] used functions calls and that makes it hard to read. If you want to parse binary data use pyconstruct [1] Relatively to regular expression and string formatting calls. From rpdooling at gmail.com Thu Jun 1 20:21:28 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 1 Jun 2006 11:21:28 -0700 Subject: os.walk trouble References: <1149173920.903876.68370@c74g2000cwc.googlegroups.com> Message-ID: <1149186088.418824.247510@h76g2000cwa.googlegroups.com> > As my first Python script, I am trying to make a program that recurses > a directory searching for files whose names match a pattern. I have a > basic idea of what the regexp would look like You probably don't need regexp for this, just use the fnmatch module http://docs.python.org/lib/module-fnmatch.html There's a great recipe in the Python Cookbook 2ed for just what you're trying to do. In fact, I believe there's a recipe in there for just about anything anybody (at the beginner or intermediate level) wants to do with Python. The recipe, with some other unrelated problems: http://tinyurl.com/nvmzg Amazon Python Cookbook link: http://www.amazon.com/exec/obidos/asin/0596007973/inscape-20 good luck rick From skip at pobox.com Thu Jun 1 20:29:55 2006 From: skip at pobox.com (skip at pobox.com) Date: Thu, 1 Jun 2006 13:29:55 -0500 Subject: Member index in toples In-Reply-To: <_TFfg.2976$EF1.229574@news20.bellglobal.com> References: <_TFfg.2976$EF1.229574@news20.bellglobal.com> Message-ID: <17535.12835.850965.102573@montanaro.dyndns.org> Alan> T = ("One","Two","Three","Four") Alan> Is there any built-in way to find what is the index of "Two" Alan> withouot looping within the tuple? One thing to consider is the different uses intended for tuples and lists. Tuples should not be treated as immutable lists, though many people use them that way. Think of lists as arrays of objects of uniform type. Think of tuples more like Pascal records or C structs. You probably want to use a list in the above case. That said, note that Python provides lots of introspection capability. Try this at an interpreter prompt: T = ("One","Two","Three","Four") L = list(T) help(L) or from a shell prompt: pydoc list The help it returns suggests that L.index("Two") will tell you the index of "Two" in L. Alan> Is the same feature available for lists or dictionaries? Dictionaries are inherently unordered. You probably want to consider the truth of this expression: "Two" in mydict for a suitably defined dictionary. It answers whether "Two" exists as a key in mydict. Skip From klaus at seistrup.dk Thu Jun 1 20:29:26 2006 From: klaus at seistrup.dk (Klaus Alexander Seistrup) Date: Thu, 1 Jun 2006 18:29:26 +0000 (UTC) Subject: Member index in toples References: <_TFfg.2976$EF1.229574@news20.bellglobal.com> Message-ID: A.M skrev: > I have a tuple like this: > > T = ("One","Two","Three","Four") > > Is there any built-in way to find what is the index of "Two" > withouot looping within the tuple? > > Is the same feature available for lists or dictionaries? Lists have an index method: #v+ >>> L = list(T) >>> L.index('Three') 2 >>> #v- Dictionaries are unordered and hence indices don't make much sense. Mvh, -- Klaus Alexander Seistrup SubZeroNet, Copenhagen, Denmark http://magnetic-ink.dk/ From michael.f.ellis at gmail.com Thu Jun 1 20:32:15 2006 From: michael.f.ellis at gmail.com (michael.f.ellis at gmail.com) Date: 1 Jun 2006 11:32:15 -0700 Subject: An oddity in list comparison and element assignment In-Reply-To: <127u81kdf70ch8d@corp.supernews.com> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> <127u81kdf70ch8d@corp.supernews.com> Message-ID: <1149186735.650036.62670@i39g2000cwa.googlegroups.com> Yes. You stated it quite precisely. I believe l1==l2 should always return True and l1==l3 should always be False. (unless l3 is reassigned as l3=l1). Your idea of a separate operator for 'all elements have numerically equal values at the moment of comparision' is a good one. For want of a better name, it could be called DeepCopyEquality(a,b) and would be equivalent to a byte-by-byte comparison of two distinct regions in memory created by a deep copies of a and b. Cheers, Mike Jim Segrave wrote: > In article <1149177617.985251.74560 at c74g2000cwc.googlegroups.com>, > wrote: > >Hi Alex, > >With all due respect to your well-deserved standing in the Python > >community, I'm not convinced that equality shouldn't imply invariance > >under identical operations. > > > >Perhaps the most fundamental notion is mathematics is that the left and > >right sides of an equation remain identical after any operation applied > >to both sides. Our experience of the physical world is similar. If I > >make identical modifications to the engines of two identical > >automobiles, I expect the difference in performance to be identical. > >If my expectation is met, I would assert that either the two vehicles > >were not identical to begin with or that my modifications were not > >performed identically. > > > >As to containers, would you say that envelope containing five $100 > >bills is the same as an envelope containing a single $100 bill and 4 > >xerox copies of it? If so, I'd like to engage in some envelope > >exchanges with you :-) > > > >As I see it, reference copying is a very useful performance and memory > >optimization. But I don't think it should undermine the validity of > >assert(a==b) as a predictor of invariance under identical operations. > > I think you end up with a totally unwieldy definition of '==' for > containers, since you have to check for _identical_ aliasing to > whatever depth it might occur, and, if you insist on equality > modeling the physical world, two lists can only be equal if: > > for each corresponding element in the two lists, either the element is > a reference to the same underlying object or the corresponding > elements are references to objects which do not have and never will > have other references bound to them. > > For example: > > ra = ['a', 'a'] > rb = ['b', 'b'] > > l1 = [ra, rb] > l2 = [ra, rb] > > This will be equal by your definition and will preserve equality over > identical operations on l1 and l2 > > l3 = [ ['a', 'b'], ['a', 'b']] > > This list will be identical, under your definition, so long as we > don't have anyone doing anything to the references ra or rb. Your > equality test has to claim that l1 and l3 are not equal, since ra > could be changed and that's not an operation on l1 or l3 > > This also leaves out the complexity of analysiing nested structures - > if you have a tuple, containing tuples which contain lists, then are > those top level tuples 'equal' if there are aliases in the lists? How > many levels deep should an equality test go? > > Does the more common test, to see if the elements of a sequence are > identical at the time of comparision need a new operator or hand > coding, since most of the time programmers aren't interested in future > equality or not of the structures. > > -- > Jim Segrave (jes at jes-2.demon.nl) From bborcic at gmail.com Thu Jun 1 20:34:11 2006 From: bborcic at gmail.com (Boris Borcic) Date: Thu, 01 Jun 2006 20:34:11 +0200 Subject: numpy bug Message-ID: <447f3338$1_7@news.bluewin.ch> after a while trying to find the legal manner to file numpy bug reports, since it's a simple one, I thought maybe a first step is to describe the bug here. Then maybe someone will direct me to the right channel. So, numpy appears not to correctly compute bitwise_and.reduce and bitwise_or.reduce : instead of reducing over the complete axis, these methods only take the extremities into account. Illustration : >>> from numpy import * >>> bitwise_or.reduce(array([8,256,32,8])) 8 >>> import numpy >>> numpy.__version__ '0.9.8' >>> Platform : Win XP SP2, Python 2.4.2 HTH, bb From anatoli.barski at googlemail.com Thu Jun 1 20:36:29 2006 From: anatoli.barski at googlemail.com (anatoli.barski at googlemail.com) Date: 1 Jun 2006 11:36:29 -0700 Subject: how to print newline in xml? In-Reply-To: References: <1149023930.292203.152540@u72g2000cwu.googlegroups.com> <1149145466.190011.146250@i39g2000cwa.googlegroups.com> Message-ID: <1149186989.073062.230220@f6g2000cwb.googlegroups.com> Thank you! I think description as an attribute is readable. But now I'm thinking about the order of attributes cause I noticed that for instance X="0" Y="0" Z="0" set in this order by my script is printed like X="0" Z="0" Y="0" therefore it could be messy - I wouldn't like the description to be somewhere between the other attributes. But I have to test it. I'll have to consider some better names for the elements Sending my regards, Anatoli From kent at kentsjohnson.com Thu Jun 1 20:36:45 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Thu, 01 Jun 2006 14:36:45 -0400 Subject: os.walk trouble In-Reply-To: <1149173920.903876.68370@c74g2000cwc.googlegroups.com> References: <1149173920.903876.68370@c74g2000cwc.googlegroups.com> Message-ID: <447f32c4_2@newspeer2.tds.net> The Prophet wrote: > As my first Python script, I am trying to make a program that recurses > a directory searching for files whose names match a pattern. If your patterns are simple (supported by fnmatch), the path module makes this very easy: import path for f in path.path(dirname).walkfiles('*.foo'): # process a .foo file here http://www.jorendorff.com/articles/python/path/index.html Kent From kent at kentsjohnson.com Thu Jun 1 20:45:56 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Thu, 01 Jun 2006 14:45:56 -0400 Subject: An oddity in list comparison and element assignment In-Reply-To: <1149177617.985251.74560@c74g2000cwc.googlegroups.com> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> Message-ID: <447f34ec$1_2@newspeer2.tds.net> michael.f.ellis at gmail.com wrote: > Hi Alex, > With all due respect to your well-deserved standing in the Python > community, I'm not convinced that equality shouldn't imply invariance > under identical operations. > > Perhaps the most fundamental notion is mathematics is that the left and > right sides of an equation remain identical after any operation applied > to both sides. Our experience of the physical world is similar. If I > make identical modifications to the engines of two identical > automobiles, I expect the difference in performance to be identical. > If my expectation is met, I would assert that either the two vehicles > were not identical to begin with or that my modifications were not > performed identically. But programming is not mathematics and assignment is not an equation. How about this: In [1]: a=3.0 In [2]: b=3 In [3]: a==b Out[3]: True In [4]: a/2 == b/2 Out[4]: False Kent From dndfan at hotpop.com Thu Jun 1 20:50:13 2006 From: dndfan at hotpop.com (The Prophet) Date: 1 Jun 2006 11:50:13 -0700 Subject: os.walk trouble In-Reply-To: <447f32c4_2@newspeer2.tds.net> References: <1149173920.903876.68370@c74g2000cwc.googlegroups.com> <447f32c4_2@newspeer2.tds.net> Message-ID: <1149187813.790336.285680@c74g2000cwc.googlegroups.com> Kent Johnson wrote: > The Prophet wrote: > > As my first Python script, I am trying to make a program that recurses > > a directory searching for files whose names match a pattern. > > If your patterns are simple (supported by fnmatch), the path module > makes this very easy: > import path > for f in path.path(dirname).walkfiles('*.foo'): > # process a .foo file here > > http://www.jorendorff.com/articles/python/path/index.html > > Kent Well, it ain't that simple, but the suggestion is helpful, since I am only a beginner. Thanks for everything, friends, now this aspect is clear to me. From jcb at iteris.com Thu Jun 1 20:50:48 2006 From: jcb at iteris.com (Metalone) Date: 1 Jun 2006 11:50:48 -0700 Subject: ctypes pointers and SendMessage In-Reply-To: References: <1149116010.351538.258990@g10g2000cwb.googlegroups.com> Message-ID: <1149187848.273374.153400@i39g2000cwa.googlegroups.com> Ok, I see what I did wrong. I forgot to define the _fields_ variable. From phleum_nospam at chello.se Thu Jun 1 20:59:13 2006 From: phleum_nospam at chello.se (Carl) Date: Thu, 01 Jun 2006 20:59:13 +0200 Subject: Starting New Process References: <1149172463.881528.131290@j55g2000cwa.googlegroups.com> <1149185284.820789.321130@y43g2000cwc.googlegroups.com> Message-ID: D wrote: > Thanks, Jean-Paul - is there any way to do it without using Twisted, > since I am not very familiar with it? (i.e. just using the os library) > Thanks. > > Jean-Paul Calderone wrote: >> On 1 Jun 2006 07:34:23 -0700, D wrote: >> >Hello, I need to write a server program that performs the following >> >tasks: >> > >> >1) Listens on TCP port 5555 for a connection >> >2) When client connects, launches application (for example, vi), then >> >closes connection with client >> >3) Goes back to listening on TCP port 5555 for an incoming connection >> >> Untested: >> >> from twisted.internet import protocol, reactor >> >> class ViRunner(protocol.Protocol): >> def connectionMade(self): >> reactor.spawnProcess( >> None, >> '/usr/bin/setsid', >> ['setsid', '/usr/bin/vi']) >> self.transport.loseConnection() >> >> f = protocol.ServerFactory() >> f.protocol = ViRunner >> reactor.listenTCP(5555, f) >> reactor.run() >> >> Jean-Paul Use import socket ifyou don't want to use twisted (which is incredibly good). Google for "+socket +python +server" and you will find what you are looking for. See, for example, http://floppsie.comp.glam.ac.uk/Glamorgan/gaius/wireless/5.html Carl From robert.kern at gmail.com Thu Jun 1 20:56:07 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 01 Jun 2006 13:56:07 -0500 Subject: numpy bug In-Reply-To: <447f3338$1_7@news.bluewin.ch> References: <447f3338$1_7@news.bluewin.ch> Message-ID: Boris Borcic wrote: > after a while trying to find the legal manner to file numpy bug reports, > since it's a simple one, I thought maybe a first step is to describe the bug > here. Then maybe someone will direct me to the right channel. Register an account on our Trac, and then you can create new tickets. We require registration because we were getting bombarded with spam tickets. http://projects.scipy.org/scipy/numpy Also, the appropriate mailing list would be numpy-discussion: http://www.scipy.org/Mailing_Lists > So, numpy appears not to correctly compute bitwise_and.reduce and > bitwise_or.reduce : instead of reducing over the complete axis, these methods > only take the extremities into account. Illustration : > > >>> from numpy import * > >>> bitwise_or.reduce(array([8,256,32,8])) > 8 Indeed. Please create a ticket. In the meantime, the .accumulate() method works correctly; you can use the last item to get the correct result for .reduce(). -- 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 kent at kentsjohnson.com Thu Jun 1 20:58:15 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Thu, 01 Jun 2006 14:58:15 -0400 Subject: Python for Visual Basic or C# programmers In-Reply-To: References: Message-ID: <447f37ce$1_1@newspeer2.tds.net> A.M wrote: > I am trying to find the equivalent functions such as vb's str or asc in > Python. Is there any resource that help me to find these kinds of functions > in Python faster? The Library Reference has a section on built-in functions: http://docs.python.org/lib/built-in-funcs.html Also take a look at the section on string methods: http://docs.python.org/lib/string-methods.html Kent From john at castleamber.com Thu Jun 1 20:59:53 2006 From: john at castleamber.com (John Bokma) Date: 1 Jun 2006 18:59:53 GMT Subject: how to print newline in xml? References: <1149023930.292203.152540@u72g2000cwu.googlegroups.com> <1149145466.190011.146250@i39g2000cwa.googlegroups.com> <1149186989.073062.230220@f6g2000cwb.googlegroups.com> Message-ID: "anatoli.barski at googlemail.com" wrote: > Thank you! I think description as an attribute is readable. But now I'm > thinking about the order of attributes cause I noticed that for > instance X="0" Y="0" Z="0" set in this order by my script is printed > like X="0" Z="0" Y="0" therefore it could be messy - I wouldn't like > the description to be somewhere between the other attributes. But I > have to test it. I don't know the library you are using, and also have way more experience in Perl. I guess that the attributes are stored in a dictionary, which has no order, and hence the original order of the attributes is lost. In Perl with some modules I use I can chose to use a list or a hash (= dictionary). With the former the original order is preserved. I am sure something like that is possible in Python as well. -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From jcb at iteris.com Thu Jun 1 21:01:43 2006 From: jcb at iteris.com (Metalone) Date: 1 Jun 2006 12:01:43 -0700 Subject: Python for Visual Basic or C# programmers In-Reply-To: <1149184981.184143.63160@f6g2000cwb.googlegroups.com> References: <1149184981.184143.63160@f6g2000cwb.googlegroups.com> Message-ID: <1149188503.783262.132870@h76g2000cwa.googlegroups.com> Slight correction. " %d" % 123 is not quite equivalent to str(123) as it does not handle negative numbers the same way. I am not sure there is a simple direct equivalent. "%+d" % 123 --> "+123" always gives a sign. "%4d" % 123 --> " 123" "%4d" % -123 --> "-123" so this works if you you know how wide the number is. This might be a little too tricky. [" %d", "%d][n < 0] % n --> selects list[0] or list[1] based upon sign of number From alanalan at newsgroup.nospam Thu Jun 1 20:55:28 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 1 Jun 2006 14:55:28 -0400 Subject: How to format datetime values Message-ID: Hi, I have a datetime value and want to format it to "June 1, 2006" shape. How can I do that? Thank you, Alan From steven.bethard at gmail.com Thu Jun 1 21:08:32 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 01 Jun 2006 13:08:32 -0600 Subject: argmax In-Reply-To: References: Message-ID: <57SdneDWRNGypuLZRVn-tg@comcast.com> David Isaac wrote: > 2. Is this a good argmax (as long as I know the iterable is finite)? > def argmax(iterable): return max(izip( iterable, count() ))[1] In Python 2.5: Python 2.5a2 (trunk:46491M, May 27 2006, 14:43:55) [MSC v.1310 32 bit (Intel)] on win32 >>> iterable = [5, 8, 2, 11, 6] >>> import operator >>> max(enumerate(iterable), key=operator.itemgetter(1)) (3, 11) STeVe From xivulon at gmail.com Thu Jun 1 21:10:54 2006 From: xivulon at gmail.com (ago) Date: 1 Jun 2006 12:10:54 -0700 Subject: win32com: how to connect to a specific instance of a running object? Message-ID: <1149189054.311477.309250@g10g2000cwb.googlegroups.com> Is it possible to use win32com.client to connect to a specific instance of a running application? In particular I am interested in finding the instance of excel which has a particular spreadsheet opened considering that there might be more instances of excel running at the same time. I need to take a "snapshot" of the spreadsheet which contains live feeds. From nicolasg at gmail.com Thu Jun 1 21:19:30 2006 From: nicolasg at gmail.com (nicolasg at gmail.com) Date: 1 Jun 2006 12:19:30 -0700 Subject: integer to binary... Message-ID: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> does anyone know a module or something to convert numbers like integer to binary format ? for example I want to convert number 7 to 0111 so I can make some bitwise operations... Thanks From rtw at freenet.co.uk Thu Jun 1 21:19:47 2006 From: rtw at freenet.co.uk (Rob Williscroft) Date: Thu, 01 Jun 2006 14:19:47 -0500 Subject: Tkinter: select multiple entries in Listbox widget? References: Message-ID: Bernard Lebel wrote in news:mailman.6413.1149178158.27775.python- list at python.org in comp.lang.python: > Hello, > > Is there an option or a way to allow the selection of multiple entries > in the Listbox widget? I could not find any, and would like to allow > the end user to select multiple entries. > > When configuring use: selectmode = "multiple" e.g.: import Tkinter as tk root = tk.Tk() a = tk.Listbox( root, selectmode = "multiple" ) for i in range(10): a.insert( i, str(i) + " item" ) a.pack() root.mainloop() I found the answer here: http://www.python.org/doc/life-preserver/ClassListbox.html Though I had to guess the `= "multiple"` part. Rob. -- http://www.victim-prime.dsl.pipex.com/ From duncanm255 at hotmail.com Thu Jun 1 21:24:47 2006 From: duncanm255 at hotmail.com (D) Date: 1 Jun 2006 12:24:47 -0700 Subject: Starting New Process In-Reply-To: References: <1149172463.881528.131290@j55g2000cwa.googlegroups.com> <1149185284.820789.321130@y43g2000cwc.googlegroups.com> Message-ID: <1149189887.279693.146240@f6g2000cwb.googlegroups.com> Sorry, I should've specified - I'm familiar with sockets, but I was referring to spawning a 'vi' process independent of my Python app.. Carl wrote: > D wrote: > > > Thanks, Jean-Paul - is there any way to do it without using Twisted, > > since I am not very familiar with it? (i.e. just using the os library) > > Thanks. > > > > Jean-Paul Calderone wrote: > >> On 1 Jun 2006 07:34:23 -0700, D wrote: > >> >Hello, I need to write a server program that performs the following > >> >tasks: > >> > > >> >1) Listens on TCP port 5555 for a connection > >> >2) When client connects, launches application (for example, vi), then > >> >closes connection with client > >> >3) Goes back to listening on TCP port 5555 for an incoming connection > >> > >> Untested: > >> > >> from twisted.internet import protocol, reactor > >> > >> class ViRunner(protocol.Protocol): > >> def connectionMade(self): > >> reactor.spawnProcess( > >> None, > >> '/usr/bin/setsid', > >> ['setsid', '/usr/bin/vi']) > >> self.transport.loseConnection() > >> > >> f = protocol.ServerFactory() > >> f.protocol = ViRunner > >> reactor.listenTCP(5555, f) > >> reactor.run() > >> > >> Jean-Paul > > Use import socket ifyou don't want to use twisted (which is incredibly > good). Google for "+socket +python +server" and you will find what you are > looking for. > > See, for example, > http://floppsie.comp.glam.ac.uk/Glamorgan/gaius/wireless/5.html > > Carl From mystilleef at gmail.com Thu Jun 1 21:27:41 2006 From: mystilleef at gmail.com (mystilleef) Date: 1 Jun 2006 12:27:41 -0700 Subject: Best Python Editor In-Reply-To: References: Message-ID: <1149190061.258740.66740@y43g2000cwc.googlegroups.com> http://scribes.sourceforge.net/ http://scribes.sourceforge.net/snippets.htm (Flash Demo) Manoj Kumar P wrote: > Hi, > > Can anyone tell me a good python editor/IDE? > It would be great if you can provide the download link also. > > Thank You, > -Manoj- > > > "SASKEN RATED Among THE Top 3 BEST COMPANIES TO WORK FOR IN INDIA - SURVEY 2005 conducted by the BUSINESS TODAY - Mercer - TNS India" > > SASKEN BUSINESS DISCLAIMER > This message may contain confidential, proprietary or legally Privileged information. In case you are not the original intended Recipient of the message, you must not, directly or indirectly, use, Disclose, distribute, print, or copy any part of this message and you are requested to delete it and inform the sender. Any views expressed in this message are those of the individual sender unless otherwise stated. Nothing contained in this message shall be construed as an offer or acceptance of any offer by Sasken Communication Technologies Limited ("Sasken") unless sent with that express intent and with due authority of Sasken. Sasken has taken enough precautions to prevent the spread of viruses. However the company accepts no liability for any damage caused by any virus transmitted by this email From uval at rz.uni-karlsruhe.de Thu Jun 1 21:28:58 2006 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Sch=FCle_Daniel?=) Date: Thu, 01 Jun 2006 21:28:58 +0200 Subject: integer to binary... In-Reply-To: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> Message-ID: nicolasg at gmail.com schrieb: > does anyone know a module or something to convert numbers like integer > to binary format ? unfortunately there is no builtin function for this >>> int("111",2) 7 >>> str(7) '7' >>> str(7,2) Traceback (most recent call last): File "", line 1, in ? TypeError: str() takes at most 1 argument (2 given) >>> int, str are not symmetrical I hope this will change in future you can use Ruby's 7.to_s(2) for this irb(main):001:0> 7.to_s(2) => "111" irb(main):002:0> 7.to_s(3) => "21" irb(main):003:0> > for example I want to convert number 7 to 0111 so I can make some > bitwise operations... you can use bitwise operations on int's anyway 7 & 3 == 3 (1 << 20) | (1 << 10) == 2**20+2**10 and so on From fredrik at pythonware.com Thu Jun 1 21:31:39 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 01 Jun 2006 21:31:39 +0200 Subject: New to Python: Do we have the concept of Hash in Python? In-Reply-To: References: Message-ID: A.M wrote: > This is my 1st day that I am seriously diving into Python and I have to > finish this application by the end of today. Maybe it wasn't a good idea to > choose the language that I don't know when I have to deliver my work in such > short time. are your boss aware of this ? From python.list at tim.thechases.com Thu Jun 1 21:36:07 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 01 Jun 2006 14:36:07 -0500 Subject: Member index in toples In-Reply-To: <_TFfg.2976$EF1.229574@news20.bellglobal.com> References: <_TFfg.2976$EF1.229574@news20.bellglobal.com> Message-ID: <447F41A7.3010108@tim.thechases.com> > I have a tuple like this: > > T = ("One","Two","Three","Four") > > Is there any built-in way to find what is the index of "Two" withouot > looping within the tuple? > > Is the same feature available for lists or dictionaries? Lists have a index() method. For the tuple, you can convert it to a list: indexOfTwo = list(T).index("Two") Dictionaries don't have a defined ordering, so there's no similar functionality (because results would be meaningless) unless you convert it to a list, and then you can snag its index in the arbitrarily-ordered results (or sort the results first). If you just need to test for presence, and don't need the index, you can use "Two" in T Just a few ideas... -tkc From rpdooling at gmail.com Thu Jun 1 21:30:42 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 1 Jun 2006 12:30:42 -0700 Subject: How to format datetime values In-Reply-To: References: Message-ID: <1149190242.446952.52180@j55g2000cwa.googlegroups.com> Are you trying to get banned, or what? It's the equivalent of me asking you: Hey, does Ruby have anything like dictionaries and will you teach me about strings? Oh, and what's an object? Go read the bleeping tutorial. rd From skip at pobox.com Thu Jun 1 21:37:51 2006 From: skip at pobox.com (skip at pobox.com) Date: Thu, 1 Jun 2006 14:37:51 -0500 Subject: How to format datetime values In-Reply-To: References: Message-ID: <17535.16911.954640.438870@montanaro.dyndns.org> Alan> I have a datetime value and want to format it to "June 1, 2006" Alan> shape. How can I do that? Again, Python's introspection capabilities to the rescue: % pydoct datetime Help on module datetime: NAME datetime - Fast implementation of the datetime type. ... class datetime(date) | datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]]) ... | strftime(...) | format -> strftime() style string. Skip From paul at eval.ca Thu Jun 1 21:38:55 2006 From: paul at eval.ca (Paul Osman) Date: Thu, 1 Jun 2006 15:38:55 -0400 Subject: How to format datetime values In-Reply-To: References: Message-ID: On 1-Jun-06, at 2:55 PM, A.M wrote: > Hi, > > > > I have a datetime value and want to format it to "June 1, 2006" > shape. How > can I do that? > > > > Thank you, > > Alan Why don't you just post the specs to your program and maybe someone will write it *FOR* you in less than a day? This is quicker than waiting for replies: Python Tutorial http://docs.python.org/tut/tut.html Module Index http://docs.python.org/modindex.html Cheers, -- Paul Osman http://www.eval.ca From greg.kujawa at gmail.com Thu Jun 1 21:35:20 2006 From: greg.kujawa at gmail.com (gregarican) Date: 1 Jun 2006 12:35:20 -0700 Subject: New to Python: Do we have the concept of Hash in Python? References: Message-ID: <1149190520.444779.314420@h76g2000cwa.googlegroups.com> We have sort of a .... problem .... here .... uh .... yeah (http://www.luminomagazine.com/2004.03/spotlight/officespace/images/lumbergh/lumbergh1.jpg)... Fredrik Lundh wrote: > A.M wrote: > > > This is my 1st day that I am seriously diving into Python and I have to > > finish this application by the end of today. Maybe it wasn't a good idea to > > choose the language that I don't know when I have to deliver my work in such > > short time. > > are your boss aware of this ? > > From grante at visi.com Thu Jun 1 21:37:13 2006 From: grante at visi.com (Grant Edwards) Date: Thu, 01 Jun 2006 19:37:13 -0000 Subject: integer to binary... References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> Message-ID: <127ugf9jgu7av18@corp.supernews.com> On 2006-06-01, nicolasg at gmail.com wrote: > does anyone know a module or something to convert numbers like integer > to binary format ? They _are_ in binary format. > for example I want to convert number 7 to 0111 so I can make some > bitwise operations... Just do it: >>> 7 & 3 3 >>> 7 | 8 15 -- Grant Edwards grante Yow! QUIET!! I'm being at CREATIVE!! Is it GREAT visi.com yet? It's s'posed to SMOKEY THE BEAR... From arv.nntp at gmail.com Thu Jun 1 21:36:33 2006 From: arv.nntp at gmail.com (Alexis Roda) Date: Thu, 01 Jun 2006 21:36:33 +0200 Subject: integer to binary... In-Reply-To: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> Message-ID: En/na nicolasg at gmail.com ha escrit: > does anyone know a module or something to convert numbers like integer > to binary format ? http://www.google.es/search?q=python+integer+to+binary http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/219300 > for example I want to convert number 7 to 0111 so I can make some > bitwise operations... python already provides some bitwise operators: http://docs.python.org/ref/summary.html HTH From nicolasg at gmail.com Thu Jun 1 21:42:20 2006 From: nicolasg at gmail.com (nicolasg at gmail.com) Date: 1 Jun 2006 12:42:20 -0700 Subject: integer to binary... In-Reply-To: <127ugf9jgu7av18@corp.supernews.com> References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> <127ugf9jgu7av18@corp.supernews.com> Message-ID: <1149190940.548582.27200@h76g2000cwa.googlegroups.com> Grant Edwards wrote: > On 2006-06-01, nicolasg at gmail.com wrote: > > > does anyone know a module or something to convert numbers like integer > > to binary format ? > > They _are_ in binary format. > > > for example I want to convert number 7 to 0111 so I can make some > > bitwise operations... > > Just do it: > > >>> 7 & 3 > 3 > >>> 7 | 8 > 15 > > > -- I know I can do that but I need to operate in every bit separeted. > Grant Edwards grante Yow! QUIET!! I'm being > at CREATIVE!! Is it GREAT > visi.com yet? It's s'posed to SMOKEY > THE BEAR... From alanalan at newsgroup.nospam Thu Jun 1 21:32:58 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 1 Jun 2006 15:32:58 -0400 Subject: Using print instead of file.write(str) Message-ID: Hi, I found print much more flexible that write method. Can I use print instead of file.write method? Thank you, Alan From python.list at tim.thechases.com Thu Jun 1 22:02:59 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 01 Jun 2006 15:02:59 -0500 Subject: integer to binary... In-Reply-To: <1149190940.548582.27200@h76g2000cwa.googlegroups.com> References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> <127ugf9jgu7av18@corp.supernews.com> <1149190940.548582.27200@h76g2000cwa.googlegroups.com> Message-ID: <447F47F3.2030505@tim.thechases.com> >>> for example I want to convert number 7 to 0111 so I can make some >>> bitwise operations... >> Just do it: >> >>>>> 7 & 3 >> 3 >>>>> 7 | 8 >> 15 > I know I can do that but I need to operate in every bit separeted. I suppose there might be other operations for which having them as strings could be handy. E.g. counting bits: bitCount = len([c for c in "01001010101" if c=="1"]) or parity checking with those counted bits...sure, it can be done with the raw stuff, but the operations often tend to be more obscure. Other reasons for wanting an arbitrary integer in binary might be for plain-old-display, especially if it represents bitmap data. If you just want to operate on each bit, you can iterate over the number of bits and shift a single bit to its position: >>> target = 10 >>> shift = 0 >>> while 1 << shift <= target: ... print "Bit %i is %i" % (shift, ... (target & (1 << shift)) >> shift) ... shift += 1 ... Bit 0 is 0 Bit 1 is 1 Bit 2 is 0 Bit 3 is 1 It's ugly, but it works... -tkc From anton.vredegoor at gmail.com Thu Jun 1 21:54:45 2006 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Thu, 01 Jun 2006 21:54:45 +0200 Subject: integer to binary... In-Reply-To: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> Message-ID: <447f4610@news.henrynet.se> nicolasg at gmail.com wrote: > does anyone know a module or something to convert numbers like integer > to binary format ? > > for example I want to convert number 7 to 0111 so I can make some > bitwise operations... >>> def bits(i,n): return tuple((0,1)[i>>j & 1] for j in xrange(n-1,-1,-1)) >>> bits(7,4) (0, 1, 1, 1) Anton From nicolasg at gmail.com Thu Jun 1 21:56:23 2006 From: nicolasg at gmail.com (nicolasg at gmail.com) Date: 1 Jun 2006 12:56:23 -0700 Subject: integer to binary... In-Reply-To: <1149190940.548582.27200@h76g2000cwa.googlegroups.com> References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> <127ugf9jgu7av18@corp.supernews.com> <1149190940.548582.27200@h76g2000cwa.googlegroups.com> Message-ID: <1149191782.973045.215080@g10g2000cwb.googlegroups.com> nicolasg at gmail.com wrote: > Grant Edwards wrote: > > On 2006-06-01, nicolasg at gmail.com wrote: > > > > > does anyone know a module or something to convert numbers like integer > > > to binary format ? > > > > They _are_ in binary format. > > > > > for example I want to convert number 7 to 0111 so I can make some > > > bitwise operations... > > > > Just do it: > > > > >>> 7 & 3 > > 3 > > >>> 7 | 8 > > 15 > > > > this is exactly what I need -> http://www.daniweb.com/code/snippet285.html thanks. > > -- > I know I can do that but I need to operate in every bit separeted. > > Grant Edwards grante Yow! QUIET!! I'm being > > at CREATIVE!! Is it GREAT > > visi.com yet? It's s'posed to SMOKEY > > THE BEAR... From grante at visi.com Thu Jun 1 21:56:07 2006 From: grante at visi.com (Grant Edwards) Date: Thu, 01 Jun 2006 19:56:07 -0000 Subject: integer to binary... References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> <127ugf9jgu7av18@corp.supernews.com> <1149190940.548582.27200@h76g2000cwa.googlegroups.com> Message-ID: <127uhinr2nr2jc4@corp.supernews.com> On 2006-06-01, nicolasg at gmail.com wrote: >>> does anyone know a module or something to convert numbers like >>> integer to binary format ? >> >> They _are_ in binary format. >> >> > for example I want to convert number 7 to 0111 so I can make some >> > bitwise operations... >> >> Just do it: >> >> >>> 7 & 3 >> 3 >> >>> 7 | 8 >> 15 > > I know I can do that but I need to operate in every bit separeted. Sorry, I've no clue what that means. -- Grant Edwards grante Yow! Now KEN is having at a MENTAL CRISIS beacuse visi.com his "R.V." PAYMENTS are OVER-DUE!! From jorgen.stenarson at bostream.nu Thu Jun 1 21:58:06 2006 From: jorgen.stenarson at bostream.nu (jorgen stenarson) Date: 1 Jun 2006 12:58:06 -0700 Subject: pyreadline 1.3 release (was UNC readline) Message-ID: <1149191886.302736.327180@i40g2000cwc.googlegroups.com> We are happy to announce the release of pyreadline 1.3. Pyreadline is based on UNC readline by Gary Bishop. UNC readline is not being developed further by Gary, and PyReadline can be considered the continuation of that project. This was done in full agreement with Gary, given his current development priorities. Pyreadline is maintained by the ipython project (http://projects.scipy.org/ipython/ipython/wiki/PyReadline/Intro). New features: * Support for international characters (if you have the correct codepage active) * Copy and paste using the clipboard * Smart paste for convenient use with ipython. Converting tab separated data to python list or numpy array. Converting file paths to use / and escaping any spaces using \ . * Pasting of multiline code removing empty lines Get it at: http://ipython.scipy.org/dist/pyreadline-1.3.win32.exe. Installations instructions are available on the pyreadline wiki. Once again we would like to thank Gary for creating this readline package. /pyreadline team From rabkinDELETE at mweb.co.za Thu Jun 1 21:58:38 2006 From: rabkinDELETE at mweb.co.za (Max) Date: Thu, 01 Jun 2006 21:58:38 +0200 Subject: Python for Visual Basic or C# programmers In-Reply-To: <1149188503.783262.132870@h76g2000cwa.googlegroups.com> References: <1149184981.184143.63160@f6g2000cwb.googlegroups.com> <1149188503.783262.132870@h76g2000cwa.googlegroups.com> Message-ID: Metalone wrote: > > This might be a little too tricky. > [" %d", "%d][n < 0] % n --> selects list[0] or list[1] based upon sign > of number > ("%+d" % 123).replace("+", " ") is slightly longer but instantly comprehensible, although I for one think your boolean indexing trick is cool. --Max From rabkinDELETE at mweb.co.za Thu Jun 1 22:01:54 2006 From: rabkinDELETE at mweb.co.za (Max) Date: Thu, 01 Jun 2006 22:01:54 +0200 Subject: how to create a cgi folder??? In-Reply-To: <1149174196.582085.5150@y43g2000cwc.googlegroups.com> References: <1149174196.582085.5150@y43g2000cwc.googlegroups.com> Message-ID: elekis wrote: > So I would like to know how to create a CGI folder ??? I installed > apache (I m under Ubuntu-linux) php and mysql cause in a first time it > was that I used. but... AFAIR it's all in the apache docs. When I did my first CGI I had no web access (still don't on this PC), so if I managed to do it, it must have been in the apache docs or python docs (and I did manage). --Max From grante at visi.com Thu Jun 1 22:04:33 2006 From: grante at visi.com (Grant Edwards) Date: Thu, 01 Jun 2006 20:04:33 -0000 Subject: integer to binary... References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> <127ugf9jgu7av18@corp.supernews.com> <1149190940.548582.27200@h76g2000cwa.googlegroups.com> <1149191782.973045.215080@g10g2000cwb.googlegroups.com> Message-ID: <127ui2hq44ki846@corp.supernews.com> On 2006-06-01, nicolasg at gmail.com wrote: >>>> does anyone know a module or something to convert numbers like integer >>>> to binary format ? >>> >>> They _are_ in binary format. >>> >>>> for example I want to convert number 7 to 0111 so I can make >>>> some bitwise operations... >>> >>> Just do it: >>> >>> >>> 7 & 3 >>> 3 >>> >>> 7 | 8 >>> 15 >> > this is exactly what I need -> http://www.daniweb.com/code/snippet285.html That's nice, but I don't register at web sites like that. >> I know I can do that but I need to operate in every bit >> separeted. I still don't get what you want a binary string for. I can see wanting a sequence (e.g. array) of boolean values, but how are you going to do bitwise operations on a binary string? -- Grant Edwards grante Yow! .. I think I'd at better go back to my DESK visi.com and toy with a few common MISAPPREHENSIONS... From iainking at gmail.com Thu Jun 1 22:08:41 2006 From: iainking at gmail.com (Iain King) Date: 1 Jun 2006 13:08:41 -0700 Subject: Trying to get FreeImagePy to work. In-Reply-To: References: <1148651668.578852.3160@i40g2000cwc.googlegroups.com> <7fEdg.13375$cX1.201311@twister2.libero.it> <1148655611.990937.322350@j73g2000cwa.googlegroups.com> <1149166096.176405.22780@i40g2000cwc.googlegroups.com> <3PCfg.20835$cX1.315781@twister2.libero.it> <1149174938.337973.85950@g10g2000cwb.googlegroups.com> Message-ID: <1149192520.959302.250840@j55g2000cwa.googlegroups.com> Michele Petrazzo wrote: > Iain King wrote: > > However, when I'm do the > > fipy.convertToPil(), it inverts the image? > > No, it not invert the image... It only return the image as is. > > > I've inserted a > > fipy.invert() before the conversion as a temporary fix, but is there a > > reason for this? > > If you are have a min-is-white image (fax ?) that isn't the standard, > you will have an "inverted" image, because PIl expect a min-is-black > image! > This is probably what is happening. I'll upload one of the images tomorrow, and you can check it out to make sure. > > relevant code: > > > > def getHeaders(files): > > thumbs = [] > > for f in files: > > print "Adding %s" % f > > fi = FIPY.Image(f) > > fi.setCurrentPage(0) > > fi.invert() #temp fix > > thumb = fi.convertToPil() > > thumb.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS) > > thumbs.append((os.path.basename(f), pilToBitmap(thumb))) > > thumbs.sort() > > return thumbs > > Just a question, why "thumbs.sort" ? Inside this list you have only > images! Ah, look closer! It's a list of tuples: (filename, image) I'll try out FIPY's resizing tomorrow too. OTOH, I have functions to convert between PIL and wxPython, and functions to convert betweem PIL and FIPY, but I don't see a function to convert FIPY to wxPython? Iain From sturnfie at gmail.com Thu Jun 1 22:08:44 2006 From: sturnfie at gmail.com (sturnfie at gmail.com) Date: 1 Jun 2006 13:08:44 -0700 Subject: Best Python Editor In-Reply-To: References: Message-ID: <1149192524.269902.46240@f6g2000cwb.googlegroups.com> In a windows enviroment, I am a big fan of conTEXT http://www.context.cx/ . Very powerful syntax highlighting for many, many languages . project workspace support . code template support . great file browsing and favorites support . good search/replace support across all open files In a unix enviroment, i use eclipse or vim -- lucas Manoj Kumar P wrote: > Hi, > > Can anyone tell me a good python editor/IDE? > It would be great if you can provide the download link also. > > Thank You, > -Manoj- From grante at visi.com Thu Jun 1 22:11:23 2006 From: grante at visi.com (Grant Edwards) Date: Thu, 01 Jun 2006 20:11:23 -0000 Subject: integer to binary... References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> <127ugf9jgu7av18@corp.supernews.com> <1149190940.548582.27200@h76g2000cwa.googlegroups.com> Message-ID: <127uifbgvsp7va9@corp.supernews.com> On 2006-06-01, Tim Chase wrote: >>>> for example I want to convert number 7 to 0111 so I can make some >>>> bitwise operations... >>> Just do it: >>> >>>>>> 7 & 3 >>> 3 >>>>>> 7 | 8 >>> 15 >> I know I can do that but I need to operate in every bit separeted. > > > I suppose there might be other operations for which having them > as strings could be handy. E.g. counting bits: > > bitCount = len([c for c in "01001010101" if c=="1"]) > > or parity checking with those counted bits...sure, it can be done > with the raw stuff, but the operations often tend to be more obscure. I would think an array or list of bits would be a lot more useful for doing "bitwise operations": bitCount = sum([0,1,0,0,1,0,1,0,1,0,1]) parity = reduce(operator.xor,[0,1,0,0,1,0,1,0,1,0,1]) > Other reasons for wanting an arbitrary integer in binary might be > for plain-old-display, especially if it represents bitmap data. Yes. I thought C should have had a %b format since the beginning, but nobody listens. But that's not what the OP said he wanted it for. -- Grant Edwards grante Yow! Now I'm concentrating at on a specific tank battle visi.com toward the end of World War II! From bdesth.quelquechose at free.quelquepart.fr Fri Jun 2 01:37:02 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 02 Jun 2006 01:37:02 +0200 Subject: Function mistaken for a method In-Reply-To: References: <447ee701$0$22029$626a54ce@news.free.fr> Message-ID: <447f4a98$0$11216$636a55ce@news.free.fr> Eric Brunel a ?crit : > On Thu, 01 Jun 2006 15:07:26 +0200, bruno at modulix > wrote: > >> Do yourself a favour : use new-style classes. >> class C(object) > > > I would if I could: I'm stuck with Python 2.1 for the moment (I should > have mentionned it; sorry for that). Err, yes - it actually makes most of my explanations inaccurate. > [snip] (snip too) From jcrocholl at googlemail.com Thu Jun 1 22:14:41 2006 From: jcrocholl at googlemail.com (Johann C. Rocholl) Date: 1 Jun 2006 13:14:41 -0700 Subject: XML-RPC server with xmlrpclib and mod_python Message-ID: <1149192881.683913.308240@g10g2000cwb.googlegroups.com> Hi all, I'm wondering what would be the best way to write an XML-RPC server using mod_python with Apache 2.0. I want the mod_python environment because the rest of my project is web-based, and Apache gives me multi-threading and everything. My first attempt implements XML-RPC introspection. Please have a look at the following files and give me a rigorous critique. All comments are welcome, even about coding style and module design. My handler for incoming mod_python requests: http://trac.browsershots.org/browser/trunk/shotserver/lib/xmlrpc/__init__.py The introspection module (I plan to have more modules in that folder): http://trac.browsershots.org/browser/trunk/shotserver/lib/xmlrpc/system.py A simple standalone test client: http://trac.browsershots.org/browser/trunk/shotserver/scripts/xmlrpc_help.py Are there any existing interfaces to use xmlrpclib with mod_python? Are there any security issues that I should be aware of when implementing XML-RPC? Thanks in advance, Johann From jes at nl.demon.net Thu Jun 1 22:14:09 2006 From: jes at nl.demon.net (Jim Segrave) Date: Thu, 01 Jun 2006 20:14:09 -0000 Subject: An oddity in list comparison and element assignment References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> <127u81kdf70ch8d@corp.supernews.com> <1149186735.650036.62670@i39g2000cwa.googlegroups.com> Message-ID: <127uikhii16hpf0@corp.supernews.com> In article <1149186735.650036.62670 at i39g2000cwa.googlegroups.com>, wrote: >Yes. You stated it quite precisely. I believe l1==l2 should always >return True and l1==l3 should always be False. (unless l3 is reassigned >as l3=l1). Your idea of a separate operator for 'all elements have >numerically equal values at the moment of comparision' is a good one. >For want of a better name, it could be called DeepCopyEquality(a,b) and >would be equivalent to a byte-by-byte comparison of two distinct >regions in memory created by a deep copies of a and b. The operator which works at the moment of comaprision is already there - that's what == does. If you really think there's a need for a comparision which includes dealing with aliasing, then it seems to me a python module with a set of functions for comparisions would make more sense. -- Jim Segrave (jes at jes-2.demon.nl) From alanalan at newsgroup.nospam Thu Jun 1 22:07:01 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 1 Jun 2006 16:07:01 -0400 Subject: How to format datetime values References: <1149190242.446952.52180@j55g2000cwa.googlegroups.com> Message-ID: "BartlebyScrivener" wrote in message news:1149190242.446952.52180 at j55g2000cwa.googlegroups.com... > Are you trying to get banned, or what? > > It's the equivalent of me asking you: > > Hey, does Ruby have anything like dictionaries and will you teach me > about strings? Oh, and what's an object? > > Go read the bleeping tutorial. > > rd > Well, I did investigate all tutorial and google and I wasn't able to find any built-in way for datetime formatting in Python. In fact I cannot find any way to format a long integer into 99,999,9999 format. I know how to format strings with C printf like formatter, but I am sure what I am trying to do can't be done with C printf formatting. I also found that mx.DateTime perfectly does date formatting and much more, but I don't want to add another step to the deployment process. >> It's the equivalent of me asking you: >> and will you teach me about strings? Oh, and what's an object? The answer to this post could be just a function name. I don't think I asked about broad concepts such as the object or strings. What I am asking here is just a clue. From bdesth.quelquechose at free.quelquepart.fr Fri Jun 2 01:45:36 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 02 Jun 2006 01:45:36 +0200 Subject: Using print instead of file.write(str) In-Reply-To: References: Message-ID: <447f4c9a$0$6174$626a54ce@news.free.fr> A.M a ?crit : > Hi, > > > I found print much more flexible that write method. Can I use print instead > of file.write method? > f = open("/path/to/file") print >> f, "this is my %s message" % "first" f.close() To print to stderr: import sys print >> sys.stderr, "oops" FWIW, you and use string formating anywhere, not only in print statements: s = "some %s and % formating" % ("nice", "cool") print s You can also use "dict formating": names = {"other": "A.M.", "me" : "bruno"} s = "hello %(other)s, my name is %(me)s" % names From jzgoda at o2.usun.pl Thu Jun 1 22:23:43 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Thu, 01 Jun 2006 22:23:43 +0200 Subject: Best Python Editor In-Reply-To: References: Message-ID: Fredrik Lundh napisa?(a): >>Can anyone tell me a good python editor/IDE? > > vim! jEdit! >>It would be great if you can provide the download link also. > > google it! google it! :D (I love these Vim <-> Emacs disputes) -- Jarek Zgoda http://jpa.berlios.de/ From alanalan at newsgroup.nospam Thu Jun 1 22:19:11 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 1 Jun 2006 16:19:11 -0400 Subject: New to Python: Do we have the concept of Hash in Python? References: Message-ID: "Fredrik Lundh" wrote in message news:mailman.6424.1149190330.27775.python-list at python.org... > A.M wrote: > >> This is my 1st day that I am seriously diving into Python and I have to >> finish this application by the end of today. Maybe it wasn't a good idea >> to choose the language that I don't know when I have to deliver my work >> in such short time. > > are your boss aware of this ? > > > > are your boss aware of this ? What is wrong with *this*? Yes, they are aware of *this*. The application is not mission critical system. It is just a simple reporting tool. From michael.f.ellis at gmail.com Thu Jun 1 22:31:01 2006 From: michael.f.ellis at gmail.com (michael.f.ellis at gmail.com) Date: 1 Jun 2006 13:31:01 -0700 Subject: An oddity in list comparison and element assignment In-Reply-To: <447f34ec$1_2@newspeer2.tds.net> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> <447f34ec$1_2@newspeer2.tds.net> Message-ID: <1149193861.211385.141940@c74g2000cwc.googlegroups.com> Considering the number of new programmers who get bit by automatic coercion, I wish Dennis Ritchie had made some different choices when he designed C. But then I doubt he ever dreamed it would become so wildly successful. Being a curmudgeon purist I'd actually prefer it if Python raised a TypeError on float vs integer comparisons. Cheers, Mike Kent Johnson wrote: > michael.f.ellis at gmail.com wrote: > > Hi Alex, > > With all due respect to your well-deserved standing in the Python > > community, I'm not convinced that equality shouldn't imply invariance > > under identical operations. > > > > Perhaps the most fundamental notion is mathematics is that the left and > > right sides of an equation remain identical after any operation applied > > to both sides. Our experience of the physical world is similar. If I > > make identical modifications to the engines of two identical > > automobiles, I expect the difference in performance to be identical. > > If my expectation is met, I would assert that either the two vehicles > > were not identical to begin with or that my modifications were not > > performed identically. > > But programming is not mathematics and assignment is not an equation. > How about this: > > In [1]: a=3.0 > > In [2]: b=3 > > In [3]: a==b > Out[3]: True > > In [4]: a/2 == b/2 > Out[4]: False > > Kent From rabkinDELETE at mweb.co.za Thu Jun 1 22:35:17 2006 From: rabkinDELETE at mweb.co.za (Max) Date: Thu, 01 Jun 2006 22:35:17 +0200 Subject: if not CGI: Message-ID: I've never done anything on the web. I mean, never developed anything. (I've got accounts on dA and wikipedia and half-a-dozen other things; I know HTML and enough JavaScript to hack away at it when friends need help). Mostly because I've never had anything worth doing: I've written a set of python CGI programs (an eCards site) and set up apache, just because I wanted to learn how. It used raw files; no database. And it sits there, working just about flawlessly, at http://localhost/maxecards/. I've even done a minor security audit, just to learn how (I met a hacker and he impressed me). But now I'm ready to do it in the real world. Nothing complicated, but a real project. And I have to choose my tools. Zope, Plone, Django, what are these? I don't have to stick with Python, although it's my preferred language. I know Python, Java and C++. But I'm ready to learn Ruby if RoR is as good as they say. I could do it in Python cgi (or mod_python). But it seems from all the hype that this is not a good way to write scaleable, extensible web applications. There's a reason I'm asking here: I like Python. But I only learned it because I had incentive (30000 local monetary units in the computer olympiad; I won 10000). Is RoR incentive enough? --Max From anatoli.barski at googlemail.com Thu Jun 1 22:39:13 2006 From: anatoli.barski at googlemail.com (anatoli.barski at googlemail.com) Date: 1 Jun 2006 13:39:13 -0700 Subject: how to print newline in xml? In-Reply-To: References: <1149023930.292203.152540@u72g2000cwu.googlegroups.com> <1149145466.190011.146250@i39g2000cwa.googlegroups.com> <1149186989.073062.230220@f6g2000cwb.googlegroups.com> Message-ID: <1149194353.343074.15140@h76g2000cwa.googlegroups.com> I use Python/XML packages are xml.dom.minidom and xml.dom.ext (second just for PrettyPrint) From michael.f.ellis at gmail.com Thu Jun 1 22:40:34 2006 From: michael.f.ellis at gmail.com (michael.f.ellis at gmail.com) Date: 1 Jun 2006 13:40:34 -0700 Subject: An oddity in list comparison and element assignment In-Reply-To: <447f152f@nntp0.pdx.net> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> <447f152f@nntp0.pdx.net> Message-ID: <1149194434.528648.148860@u72g2000cwu.googlegroups.com> Yes (unless I was testing the assertion that the second envelope did not contain counterfeits of the first) Scott David Daniels wrote: > Would you say that envelope containing five $100 bills is equal to > an envelope containing five $100 bills with different serial numbers? From 3dbernard at gmail.com Thu Jun 1 22:45:44 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 1 Jun 2006 16:45:44 -0400 Subject: Tkinter: select multiple entries in Listbox widget? In-Reply-To: References: Message-ID: <61d0e2b40606011345jfa64a17i12e6825fd75d87e0@mail.gmail.com> Oh, thanks a lot Rob. Bernard On 6/1/06, Rob Williscroft wrote: > Bernard Lebel wrote in news:mailman.6413.1149178158.27775.python- > list at python.org in comp.lang.python: > > > Hello, > > > > Is there an option or a way to allow the selection of multiple entries > > in the Listbox widget? I could not find any, and would like to allow > > the end user to select multiple entries. > > > > > > When configuring use: > > selectmode = "multiple" > > e.g.: > > import Tkinter as tk > > root = tk.Tk() > > a = tk.Listbox( root, selectmode = "multiple" ) > for i in range(10): > a.insert( i, str(i) + " item" ) > > a.pack() > root.mainloop() > > I found the answer here: > > http://www.python.org/doc/life-preserver/ClassListbox.html > > Though I had to guess the `= "multiple"` part. > > Rob. > -- > http://www.victim-prime.dsl.pipex.com/ > -- > http://mail.python.org/mailman/listinfo/python-list > From max at alcyone.com Thu Jun 1 22:47:10 2006 From: max at alcyone.com (Erik Max Francis) Date: Thu, 01 Jun 2006 13:47:10 -0700 Subject: An oddity in list comparison and element assignment In-Reply-To: <1149177617.985251.74560@c74g2000cwc.googlegroups.com> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> Message-ID: <6dKdnVnjh5LTz-LZnZ2dnUVZ_qmdnZ2d@speakeasy.net> michael.f.ellis at gmail.com wrote: > With all due respect to your well-deserved standing in the Python > community, I'm not convinced that equality shouldn't imply invariance > under identical operations. Doo you really want 2 == 2.0 to be False? -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Without victory there is no survival. -- Winston Churchill From alanalan at newsgroup.nospam Thu Jun 1 22:37:31 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 1 Jun 2006 16:37:31 -0400 Subject: New to Python: Do we have the concept of Hash in Python? References: Message-ID: <%aIfg.3027$EF1.232063@news20.bellglobal.com> "Fredrik Lundh" wrote in message news:mailman.6424.1149190330.27775.python-list at python.org... > A.M wrote: > >> This is my 1st day that I am seriously diving into Python and I have to >> finish this application by the end of today. Maybe it wasn't a good idea >> to choose the language that I don't know when I have to deliver my work >> in such short time. > > are your boss aware of this ? > > > > are your boss aware of this ? In fact my boss is quite impressed with my progress so far. I am a little confused about the fact that you got frustrated with my posts today. I am not asking for a big tutorial or deepest philosophy behind the concepts. The answer to this post could be just the word "Dictionary" which is 10 key stroke ! Does this hurt? From yan at NsOeSiPnAeMr.com Thu Jun 1 23:04:40 2006 From: yan at NsOeSiPnAeMr.com (Captain Dondo) Date: Thu, 01 Jun 2006 14:04:40 -0700 Subject: Replace one element of a tuple Message-ID: <127ulhn6h7hvj22@corp.supernews.com> I have an array(?) (sorry, I'm new* to python so I'm probably mangling the terminology) that looks like this: [((1028L, datetime.datetime(2006, 5, 30, 7, 0), datetime.datetime(2006, 5, 30, 7, 30), 'Arthur', 'Prunella Sees the Light; Return of the Snowball', 'Prunella prepares for a sleepover with Marina; D.W. protects a snowball.', 'Children', 'tooth.seiner.lan', None, 0L, None, 1L, 1L, 'Default', 9L, 'SH044107', 'EP0441070123', datetime.datetime(2006, 5, 30, 7, 31, 24), 1164179392L, 0.0, 1, datetime.date(2002, 11, 28), 0, 0L, 0),), ((1028L, datetime.datetime(2006, 5, 4, 10, 0), datetime.datetime(2006, 5, 4, 10, 30), 'Bob the Builder', 'Using Clues', '', 'Children', 'tooth.seiner.lan', None, 0L, None, 1L, 1L, 'Default', 6L, 'SH326087', 'EP3260870141', datetime.datetime(2006, 5, 4, 10, 31, 30), 1163673536L, 0.0, 1, datetime.date(2005, 3, 19), 0, 0L, 0),)] I want to replace every instance of 'tooth.seiner.lan' with 'localhost'. There may be lots and lots of these entries (they're pulled from my mythtv database). I could brute-force this by rewriting the whole thing and replacing every 9th element but there has to be a better way.... I've looked at various search-and-replace snippets but none that address what I am trying to do.... --Yan *I'm not really new to python, just very very rusty. Last time I used it was about 3 years ago, and I was equally clueless.... From peter-gsellmann at eunet.at Thu Jun 1 23:16:17 2006 From: peter-gsellmann at eunet.at (Peter Gsellmann) Date: Thu, 01 Jun 2006 23:16:17 +0200 Subject: WinPops References: <1149132789_5889@sp6iad.superfeed.net> Message-ID: <447f5781$0$15793$14726298@news.sunsite.dk> Roger Upole wrote: > > "Hari Sekhon" wrote in message > news:mailman.6230.1148640634.27775.python-list at python.org... >> Hi, >> Is there a way of sending winpops (Windows Pop-Up / Net Send messages) >> in python? >> >> Perhaps some library or something that I can use under both Windows and >> Linux? >> >> Hari > > On Windows, you can use win32net.NetMessageBufferSend. > > Roger > On Linux, i use the smbclient binary: from subprocess import * q=Popen(['smbclient','-M','maggy'],stdin=PIPE) q.stdin.write('hello!') q.stdin.close() q.wait() Peter From joh12005 at yahoo.fr Thu Jun 1 23:17:22 2006 From: joh12005 at yahoo.fr (joh12005 at yahoo.fr) Date: 1 Jun 2006 14:17:22 -0700 Subject: grouping a flat list of number by range Message-ID: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> hello, i'm looking for a way to have a list of number grouped by consecutive interval, after a search, for example : [3, 6, 7, 8, 12, 13, 15] => [[3, 4], [6,9], [12, 14], [15, 16]] (6, not following 3, so 3 => [3:4] ; 7, 8 following 6 so 6, 7, 8 => [6:9], and so on) i was able to to it without generators/yield but i think it could be better with them, may be do you an idea? best regards, J. From mensanator at aol.com Thu Jun 1 23:25:10 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 1 Jun 2006 14:25:10 -0700 Subject: integer to binary... References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> Message-ID: <1149197110.225383.107770@f6g2000cwb.googlegroups.com> nicolasg at gmail.com wrote: > does anyone know a module or something to convert numbers like integer > to binary format ? > > for example I want to convert number 7 to 0111 so I can make some > bitwise operations... > > Thanks Use the gmpy module. >>> import gmpy >>> a = 14 >>> b = 7 >>> c = 8 >>> help(gmpy.digits) Help on built-in function digits: digits(...) digits(x[,base]): returns Python string representing x in the given base (2 to 36, default 10 if omitted or 0); leading '-' present if x<0, but no leading '+' if x>=0. x must be an mpz, or else gets coerced into one. >>> print gmpy.digits(a,2) 1110 >>> print gmpy.digits(b,2) 111 >>> print gmpy.digits(c,2) 1000 >>> help(gmpy.setbit) Help on built-in function setbit: setbit(...) setbit(x,n,v=1): returns a copy of the value of x, with bit n set to value v; n must be an ordinary Python int, >=0; v, 0 or !=0; x must be an mpz, or else gets coerced to one. >>> d = gmpy.setbit(c,1,1) >>> print gmpy.digits(d,2) 1010 >>> help(gmpy.scan1) Help on built-in function scan1: scan1(...) scan1(x, n=0): returns the bit-index of the first 1-bit of x (that is at least n); n must be an ordinary Python int, >=0. If no more 1-bits are in x at or above bit-index n (which can only happen for x>=0, notionally extended with infinite 0-bits), None is returned. x must be an mpz, or else gets coerced to one. >>> help(gmpy.scan0) Help on built-in function scan0: scan0(...) scan0(x, n=0): returns the bit-index of the first 0-bit of x (that is at least n); n must be an ordinary Python int, >=0. If no more 0-bits are in x at or above bit-index n (which can only happen for x<0, notionally extended with infinite 1-bits), None is returned. x must be an mpz, or else gets coerced to one. >>> print gmpy.scan1(a) 1 >>> print gmpy.scan1(b) 0 >>> print gmpy.scan1(c) 3 >>> print gmpy.scan1(d) 1 >>> print gmpy.scan0(a) 0 >>> print gmpy.scan0(b) 3 >>> print gmpy.scan0(c) 0 >>> print gmpy.scan0(d) 0 >>> help(gmpy.popcount) Help on built-in function popcount: popcount(...) popcount(x): returns the number of 1-bits set in x; note that this is 'infinite' if x<0, and in that case, -1 is returned. x must be an mpz, or else gets coerced to one. >>> print gmpy.popcount(a) 3 >>> print gmpy.popcount(b) 3 >>> print gmpy.popcount(c) 1 >>> print gmpy.popcount(d) 2 >>> help(gmpy.hamdist) Help on built-in function hamdist: hamdist(...) hamdist(x,y): returns the Hamming distance (number of bit-positions where the bits differ) between x and y. x and y must be mpz, or else get coerced to mpz. >>> print gmpy.hamdist(a,b) 2 >>> print gmpy.hamdist(a,c) 2 >>> print gmpy.hamdist(a,d) 1 >>> print gmpy.hamdist(b,c) 4 >>> print gmpy.hamdist(b,d) 3 >>> print gmpy.hamdist(c,d) 1 From joncle at googlemail.com Thu Jun 1 23:33:21 2006 From: joncle at googlemail.com (Jon Clements) Date: 1 Jun 2006 14:33:21 -0700 Subject: Using print instead of file.write(str) In-Reply-To: <447f4c9a$0$6174$626a54ce@news.free.fr> References: <447f4c9a$0$6174$626a54ce@news.free.fr> Message-ID: <1149197601.238826.151200@f6g2000cwb.googlegroups.com> Didn't know of the >> syntax: lovely to know about it Bruno - thank you. To the OP - I find the print statement useful for something like: print 'this','is','a','test' >>> 'this is a test' (with implicit newline and implicit spacing between parameters) If you want more control (more flexibility, perhaps?) over the formatting of the output: be it spacing between parameters or newline control, use the methods Bruno describes below. I'm not sure if you can suppress the spacing between elements (would love to be corrected though); to stop the implicit newline use something like print 'testing', >>> 'testing' (but - with the leading comma, the newline is suppressed) I personally find that print is convenient for sentences (or writing 'lines'). Thought it worth pointing this out in case, like some I know, you come across a cropper with certain output streams. All the best, Jon. Bruno Desthuilliers wrote: > A.M a ?crit : > > Hi, > > > > > > I found print much more flexible that write method. Can I use print instead > > of file.write method? > > > > f = open("/path/to/file") > print >> f, "this is my %s message" % "first" > f.close() > > To print to stderr: > > import sys > print >> sys.stderr, "oops" > > FWIW, you and use string formating anywhere, not only in print statements: > > s = "some %s and % formating" % ("nice", "cool") > print s > > You can also use "dict formating": > > names = {"other": "A.M.", "me" : "bruno"} > s = "hello %(other)s, my name is %(me)s" % names From akameswaran at gmail.com Thu Jun 1 23:33:41 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 1 Jun 2006 14:33:41 -0700 Subject: Replace one element of a tuple In-Reply-To: <127ulhn6h7hvj22@corp.supernews.com> References: <127ulhn6h7hvj22@corp.supernews.com> Message-ID: <1149197621.047337.135070@c74g2000cwc.googlegroups.com> Captain Dondo wrote: > I have an array(?) (sorry, I'm new* to python so I'm probably mangling > the terminology) that looks like this: > > [((1028L, datetime.datetime(2006, 5, 30, 7, 0), datetime.datetime(2006, > 5, 30, 7, 30), 'Arthur', 'Prunella Sees the Light; Return of the > Snowball', 'Prunella prepares for a sleepover with Marina; D.W. protects > a snowball.', 'Children', 'tooth.seiner.lan', None, 0L, None, 1L, 1L, > 'Default', 9L, 'SH044107', 'EP0441070123', datetime.datetime(2006, 5, > 30, 7, 31, 24), 1164179392L, 0.0, 1, datetime.date(2002, 11, 28), 0, 0L, > 0),), ((1028L, datetime.datetime(2006, 5, 4, 10, 0), > datetime.datetime(2006, 5, 4, 10, 30), 'Bob the Builder', 'Using Clues', > '', 'Children', 'tooth.seiner.lan', None, 0L, None, 1L, 1L, 'Default', > 6L, 'SH326087', 'EP3260870141', datetime.datetime(2006, 5, 4, 10, 31, > 30), 1163673536L, 0.0, 1, datetime.date(2005, 3, 19), 0, 0L, 0),)] > > I want to replace every instance of 'tooth.seiner.lan' with 'localhost'. > There may be lots and lots of these entries (they're pulled from my > mythtv database). > > I could brute-force this by rewriting the whole thing and replacing > every 9th element but there has to be a better way.... > > I've looked at various search-and-replace snippets but none that address > what I am trying to do.... > > --Yan > > *I'm not really new to python, just very very rusty. Last time I used > it was about 3 years ago, and I was equally clueless.... There's a lot of parenthesis :) not easy to read, but unless I'm seeing something odd, you have string literals in a tuple. So I don't think your going to find a better way than brute force recreation. FYI lists are between [] and are mutable Tuples are between () and are immutable. If I'm countin paren's right you have a list that contains a tuple, that contains another tuple with 1 element in it. so you can recreate the tuples... or convert the whole thing to a list of lists. From chris at kateandchris.net Thu Jun 1 23:39:16 2006 From: chris at kateandchris.net (Chris Lambacher) Date: Thu, 1 Jun 2006 17:39:16 -0400 Subject: Add file to zip, or replace file in zip In-Reply-To: <447D417D.000005.13553@bj163app13.163.com> References: <447D417D.000005.13553@bj163app13.163.com> Message-ID: <20060601213916.GA912@kateandchris.net> Skip over the file in question when you first are zipping the directory. Unfortunately you cannot replace or remove a file from a zip without unzipping and rezipping all the contents. -Chris On Wed, May 31, 2006 at 03:10:53PM +0800, majj81 wrote: > hi: > Good afternoon. > Has this problem solved in the URL > [1]http://mail.python.org/pipermail/python-list/2006-April/338849.html . > Now I have the same problem to deal with. If you have any suggestion > please tell me. > Thanks. > Johnny Ma > come from China > > > > > ?? ?? ?? ?? ?? 1/2? ?? ?? ?????? ?? ?? ?? ?? ?? > [2]?? ? ?? ?? '? ?? ?? ?? ?? ?? 1/2? ?? ?? ?? 1/4 1/4 ?? ????'' ?? Ajax > 1/4 1/4 ????126 ??D 1/4? ?????? ?? ?? ?? ?? ?? > > References > > Visible links > 1. http://mail.python.org/pipermail/python-list/2006-April/338849.html > 2. http://www.126.com/ > -- > http://mail.python.org/mailman/listinfo/python-list From sjmachin at lexicon.net Thu Jun 1 23:48:29 2006 From: sjmachin at lexicon.net (John Machin) Date: Fri, 02 Jun 2006 07:48:29 +1000 Subject: struct: type registration? In-Reply-To: References: <447e4b98$1@news.eftel.com> <447EDF7C.3080104@lexicon.net> Message-ID: <447F60AD.9020506@lexicon.net> On 2/06/2006 3:44 AM, Giovanni Bajo wrote: > John Machin wrote: > >>> Looks like you totally misread my message. >> Not at all. >> >> Your function: >> >> def mystring_pack(s): >> if len(s) > 20: >> raise ValueError, "a mystring can be at max 20 chars" >> s = (s + "\0"*20)[:20] >> s = struct.pack("20s", s) >> return s >> >> can be even better replaced by (after reading the manual "For packing, >> the string is truncated or padded with null bytes as appropriate to >> make it fit.") by: >> >> def mystring_pack(s): >> if len(s) > 20: >> raise ValueError, "a mystring can be at max 20 chars" >> return s >> # return s = (s + "\0"*20)[:20] # not needed, according to the >> manual # s = struct.pack("20s", s) >> # As I said, this particular instance of using struct.pack is a >> big fat no-op. > > John, the point of the example was to show that one could write custom > packer/unpacker which calls struct.pack/unpack and, after that, > post-processes the results to obtain some custom data type. What you appear to be doing is proposing an API for extending struct by registering custom type-codes (ASCII alphabetic?) each requiring three call-back functions (mypacker, myunpacker, mylength). Example registration for an "S" string (fixed storage length, true length determined on unpacking by first occurrence of '\0' (if any)). struct.register("S", packerS, unpackerS, lengthS) You give no prescription for what those functions should do. You provide "examples" which require reverse engineering to deduce of what they are intended to be exemplars. Simple-minded folk like myself might expect that the functions would work something like this: Packing: when struct.pack reaches the custom code in the format, it does this (pseudocode): obj = _get_next_arg() itemstrg = mypacker(obj) _append_to_output_string(itemstrg) Unpacking: when struct.unpack reaches a custom code in the format, it does this (pseudocode): n = mylength() # exception if < n bytes remain obj = myunpacker(remaining_bytes[:n]) _append_to_output_tuple(obj) Thus, in a simple case like the NUL-terminated string: def lengthS(): return 20 def packerS(s): assert len(s) <= 20 return s.ljust(20, '\0') # alternatively, return struct.pack("20s", s) def unpackerS(bytes): assert len(bytes) == 20 i = bytes.find('\0') if i >= 0: return bytes[:i] return bytes In more complicated cases, it may be useful for either/both the packer/unpacker custom functions to call struct.pack/unpack to assist in the assembly/disassembly exercise. This should be (1) possible without perturbing the state of the outer struct.pack/unpack invocation (2) sufficiently obvious to warrant little more than a passing mention. > Now, I apologize > if my example wasn't exactly the shortest, most compact, most pythonic piece > of code. It was not meant to be. It was meant to be very easy to read and > very clear in what it is being done. You are nitpicking that part of my code > is a no-op. Fine. Scarcely a nitpick. It was very clear that parts of it were doing absolutely nothing in a rather byzantine & baroque fashion. What was unclear was whether this was by accident or design. You say (*after* the examples) that "As shown, the custom packer/unpacker can call the original pack/unpack as a basis for their work. ... when called recursively ...". What basis for what work? As for recursion, I see no "19s", "18s", etc here :-) > Sorry if this confused you. It didn't. As a self-confessed idiot, I am resolutely and irredeemably unconfused. > I was just trying to show a > simple pattern: > > custom packer: adjust data, call struct.pack(), return > custom unpacker: call struct.unpack(), adjust data, return > > I should have chosen a most complex example probably, but I did not want to > confuse readers. It seems I have confused them by choosing too simple an > example. The problem was that you chose an example that had minimal justification (i.e. only the length check) for a custom packer at all (struct.pack pads the "s" format with NUL bytes) and no use at all for a call to struct.unpack inside the custom unpacker. Cheers, John From joncle at googlemail.com Thu Jun 1 23:49:53 2006 From: joncle at googlemail.com (Jon Clements) Date: 1 Jun 2006 14:49:53 -0700 Subject: Using print instead of file.write(str) In-Reply-To: <1149197601.238826.151200@f6g2000cwb.googlegroups.com> References: <447f4c9a$0$6174$626a54ce@news.free.fr> <1149197601.238826.151200@f6g2000cwb.googlegroups.com> Message-ID: <1149198592.996237.116760@j55g2000cwa.googlegroups.com> I meant 'trailing': not leading. mea culpa. Jon. Jon Clements wrote: > Didn't know of the >> syntax: lovely to know about it Bruno - thank > you. > > To the OP - I find the print statement useful for something like: > print 'this','is','a','test' > >>> 'this is a test' > (with implicit newline and implicit spacing between parameters) > > If you want more control (more flexibility, perhaps?) over the > formatting of the output: be it spacing between parameters or newline > control, use the methods Bruno describes below. > > I'm not sure if you can suppress the spacing between elements (would > love to be corrected though); to stop the implicit newline use > something like > print 'testing', > >>> 'testing' > (but - with the leading comma, the newline is suppressed) > > I personally find that print is convenient for sentences (or writing > 'lines'). > > Thought it worth pointing this out in case, like some I know, you come > across a cropper with certain output streams. > > All the best, > > Jon. > > > > Bruno Desthuilliers wrote: > > A.M a ?crit : > > > Hi, > > > > > > > > > I found print much more flexible that write method. Can I use print instead > > > of file.write method? > > > > > > > f = open("/path/to/file") > > print >> f, "this is my %s message" % "first" > > f.close() > > > > To print to stderr: > > > > import sys > > print >> sys.stderr, "oops" > > > > FWIW, you and use string formating anywhere, not only in print statements: > > > > s = "some %s and % formating" % ("nice", "cool") > > print s > > > > You can also use "dict formating": > > > > names = {"other": "A.M.", "me" : "bruno"} > > s = "hello %(other)s, my name is %(me)s" % names From maric at aristote.info Thu Jun 1 23:54:51 2006 From: maric at aristote.info (Maric Michaud) Date: Thu, 1 Jun 2006 23:54:51 +0200 Subject: An oddity in list comparison and element assignment In-Reply-To: <1149177617.985251.74560@c74g2000cwc.googlegroups.com> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> Message-ID: <200606012354.52702.maric@aristote.info> Le Jeudi 01 Juin 2006 18:00, michael.f.ellis at gmail.com a ?crit?: > Perhaps the most fundamental notion is mathematics is that the left and > right sides of an equation remain identical after any operation applied > to both sides. IMHO, you are not aware that the '=' symbol of mathematics exists in python, it's the 'is' assertion. a is b and then, do what you want with a (or b), a is b remains True. THIS is the meaning of expr1 = expr2, but in computer science, this is not as important as it is in pure logic (most languages do not even provide the 'is' assertion). -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From __peter__ at web.de Thu Jun 1 23:53:41 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Jun 2006 23:53:41 +0200 Subject: grouping a flat list of number by range References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> Message-ID: joh12005 at yahoo.fr wrote: > i'm looking for a way to have a list of number grouped by consecutive > interval, after a search, for example : > > [3, 6, 7, 8, 12, 13, 15] > > => > > [[3, 4], [6,9], [12, 14], [15, 16]] > > (6, not following 3, so 3 => [3:4] ; 7, 8 following 6 so 6, 7, 8 => > [6:9], and so on) > > i was able to to it without generators/yield but i think it could be > better with them, may be do you an idea? Don't hold back your code. Would it work to replace each occurrence of result_list.append([start, stop]) with yield [start, stop] ? Peter From rpdooling at gmail.com Thu Jun 1 23:55:46 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 1 Jun 2006 14:55:46 -0700 Subject: Replace one element of a tuple In-Reply-To: <127ulhn6h7hvj22@corp.supernews.com> References: <127ulhn6h7hvj22@corp.supernews.com> Message-ID: <1149198946.567904.260480@f6g2000cwb.googlegroups.com> >> I've looked at various search-and-replace snippets but none that address >> what I am trying to do.... I think you need to tell more about what you're trying to do. You say it's in a database? Is that why you can't just put the whole blob in your text editor and do search-and-replace? And is that also why you can't turn it into a giant string and do giantstring.replace('unwanted','wanted') rd From alanalan at newsgroup.nospam Thu Jun 1 23:45:02 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 1 Jun 2006 17:45:02 -0400 Subject: Using print instead of file.write(str) References: <447f4c9a$0$6174$626a54ce@news.free.fr> <1149197601.238826.151200@f6g2000cwb.googlegroups.com> Message-ID: Yes, it saved my time big time. Thank you Bruno. I use the print >>>file to generate HTML files. print is very flexible and nice. The dictionary formatting that Brunto said is awesome! Thanks again, Alan "Jon Clements" wrote in message news:1149197601.238826.151200 at f6g2000cwb.googlegroups.com... Didn't know of the >> syntax: lovely to know about it Bruno - thank you. To the OP - I find the print statement useful for something like: print 'this','is','a','test' >>> 'this is a test' (with implicit newline and implicit spacing between parameters) If you want more control (more flexibility, perhaps?) over the formatting of the output: be it spacing between parameters or newline control, use the methods Bruno describes below. I'm not sure if you can suppress the spacing between elements (would love to be corrected though); to stop the implicit newline use something like print 'testing', >>> 'testing' (but - with the leading comma, the newline is suppressed) I personally find that print is convenient for sentences (or writing 'lines'). Thought it worth pointing this out in case, like some I know, you come across a cropper with certain output streams. All the best, Jon. Bruno Desthuilliers wrote: > A.M a ?crit : > > Hi, > > > > > > I found print much more flexible that write method. Can I use print > > instead > > of file.write method? > > > > f = open("/path/to/file") > print >> f, "this is my %s message" % "first" > f.close() > > To print to stderr: > > import sys > print >> sys.stderr, "oops" > > FWIW, you and use string formating anywhere, not only in print statements: > > s = "some %s and % formating" % ("nice", "cool") > print s > > You can also use "dict formating": > > names = {"other": "A.M.", "me" : "bruno"} > s = "hello %(other)s, my name is %(me)s" % names From michael.f.ellis at gmail.com Thu Jun 1 23:57:49 2006 From: michael.f.ellis at gmail.com (michael.f.ellis at gmail.com) Date: 1 Jun 2006 14:57:49 -0700 Subject: An oddity in list comparison and element assignment In-Reply-To: <6dKdnVnjh5LTz-LZnZ2dnUVZ_qmdnZ2d@speakeasy.net> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> <6dKdnVnjh5LTz-LZnZ2dnUVZ_qmdnZ2d@speakeasy.net> Message-ID: <1149199069.871245.270330@f6g2000cwb.googlegroups.com> Truthfully, I wouldn't mind it at all. In Python, I frequently write things like i == int(f) or vice versa just to avoid subtle bugs that sometimes creep in when later modifications to code change the original assumptions. When working in C, I always set the compiler for maximum warnings and do my damndest to make them all go away. In the long run, time spent on rigorous coding always repays itself with interest in time saved debugging. Mike Erik Max Francis wrote: > michael.f.ellis at gmail.com wrote: > > > With all due respect to your well-deserved standing in the Python > > community, I'm not convinced that equality shouldn't imply invariance > > under identical operations. > > Doo you really want > > 2 == 2.0 > > to be False? > > -- > Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ > San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis > Without victory there is no survival. > -- Winston Churchill From jjl at pobox.com Fri Jun 2 00:02:17 2006 From: jjl at pobox.com (John J. Lee) Date: 01 Jun 2006 22:02:17 +0000 Subject: Finding a lost PYTHONPATH with find References: <87zmh2oxwr.fsf@pobox.com> Message-ID: <87ac8wedqu.fsf@pobox.com> Edward Elliott writes: > John J. Lee wrote: > > > find / -maxdepth 3 -size -100k -type f -exec grep -sli pythonpath '{}' \; > > > > > > The minus in '-100k' (meaning "less than 100k") seems to be > > undocumented, at least on my system. > > It should be standard in linux man pages, can't speak for other unices: > > TESTS > Numeric arguments can be specified as > > +n for greater than n, > > -n for less than n, > > n for exactly n. > > Maybe you were fooled because it's not directly under the description of > -size. Yes, that's right -- thanks. > > I suppose the -maxdepth is > > redundant since I think find searches breadth-first by default. > > ??? maxdepth determines how deep the search will look, not the order the > search occurs. Your search only find things within 3 levels of the root, > unless your directory tree goes no deeper than that (very unlikely) the > maxdepth can't be redundant. It can if you hit Control-C as soon as it finds the damn thing :-) -- which is exactly what I would have done, of course. John From jjl at pobox.com Fri Jun 2 00:08:25 2006 From: jjl at pobox.com (John J. Lee) Date: 01 Jun 2006 22:08:25 +0000 Subject: urllib2 and HTTP 302 References: <4476C7A6.5040506@designaproduct.biz> Message-ID: <8764jkedgm.fsf@pobox.com> Laszlo Nagy writes: [...] > how can I return the redirection URL? > I tried to get this information from the exception but I could not. Is > it possible to read it from the openerdirector? > Any suggestions? > > > try: > self.post_multipart( > url, > [('uploadType','Inventory')], > [('uploadFileName','inv.txt',fdata)] > ) > except urllib2.HTTPError, e: > if e.code == 302: > return "I would like to get the URL to be redirected > to...." > else: > raise redirected_url = e.geturl() John From slawomir.nowaczyk.847 at student.lu.se Thu Jun 1 23:56:10 2006 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Thu, 01 Jun 2006 23:56:10 +0200 Subject: An oddity in list comparison and element assignment In-Reply-To: <1149194434.528648.148860@u72g2000cwu.googlegroups.com> References: <447f152f@nntp0.pdx.net> <1149194434.528648.148860@u72g2000cwu.googlegroups.com> Message-ID: <20060601234417.FC2E.SLAWOMIR.NOWACZYK.847@student.lu.se> On Thu, 01 Jun 2006 13:40:34 -0700 michael.f.ellis at gmail.com wrote: #> Scott David Daniels wrote: #> > Would you say that envelope containing five $100 bills is equal to #> > an envelope containing five $100 bills with different serial numbers? #> Yes (unless I was testing the assertion that the second envelope did #> not contain counterfeits of the first) So, what if Bank of America later decided that bills with serial numbers containing "7" are no longer valid? In other word, *if* you assume equality must be preserved by future modifications, than no two different (modifiable) objects can ever be really equal. -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) I believe that math illiteracy affects 7 out of every 5 people. From jes at nl.demon.net Fri Jun 2 00:11:21 2006 From: jes at nl.demon.net (Jim Segrave) Date: Thu, 01 Jun 2006 22:11:21 -0000 Subject: grouping a flat list of number by range References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> Message-ID: <127upg9qbf0b3f2@corp.supernews.com> In article <1149196642.001466.53990 at c74g2000cwc.googlegroups.com>, wrote: >hello, > >i'm looking for a way to have a list of number grouped by consecutive >interval, after a search, for example : > >[3, 6, 7, 8, 12, 13, 15] > >=> > >[[3, 4], [6,9], [12, 14], [15, 16]] > >(6, not following 3, so 3 => [3:4] ; 7, 8 following 6 so 6, 7, 8 => >[6:9], and so on) > >i was able to to it without generators/yield but i think it could be >better with them, may be do you an idea? There are probably better ways, but this works > >best regards, > >J. class IterInterval(object): """Create an iterator which, given a list of integers, for each run of consecutive integers i...j, yields a two element list [i, j + 1] Singleton lists [i] return [i, i + 1] Empty lists return None """ def __init__(self, seq): self.seq = seq self.firstval = None self.index = 0 def __iter__(self): # firstval = the start of a run of consecutive integers # lastval = the last value found in the run # nextval = the most recent value taken from the input list if not self.firstval: # set up the first iteration if self.index >= len(self.seq): # empty list, return raise StopIteration self.firstval = lastval = int(self.seq[self.index]) self.index += 1 while True: if self.index >= len(self.seq): # list exhausted, output the last value read yield [self.firstval, lastval + 1] raise StopIteration nextval = int(self.seq[self.index]) self.index += 1 if nextval == lastval + 1: lastval = nextval continue else: # end of run - output the run, reset for next call yield [self.firstval, lastval + 1] self.firstval = lastval = nextval continue if __name__ == '__main__': for l in [[3, 6, 7, 8, 12, 13, 15], [2], []]: print l, "=>", [lst for lst in IterInterval(l)] /usr/home/jes% python interval.py [3, 6, 7, 8, 12, 13, 15] => [[3, 4], [6, 9], [12, 14], [15, 16]] [3] => [[3, 4]] [] => [] -- Jim Segrave (jes at jes-2.demon.nl) From michael.f.ellis at gmail.com Fri Jun 2 00:12:23 2006 From: michael.f.ellis at gmail.com (michael.f.ellis at gmail.com) Date: 1 Jun 2006 15:12:23 -0700 Subject: An oddity in list comparison and element assignment References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> Message-ID: <1149199942.955228.281950@u72g2000cwu.googlegroups.com> I believe that 'is' tests equality of reference, such that >>> a = range(1,3) >>> b = range(1,3) >>> a is b False The 'is' operator tells you whether a and b refer to the same object. What I've been discussing is whether == should test for "structural" equality so that a and b remain equivalent under parallel mutations (and also under single mutations to common references) Cheers, Mike Maric Michaud wrote: > Le Jeudi 01 Juin 2006 18:00, michael.f.ellis at gmail.com a ?crit : > > Perhaps the most fundamental notion is mathematics is that the left and > > right sides of an equation remain identical after any operation applied > > to both sides. > > IMHO, you are not aware that the '=' symbol of mathematics exists in python, > it's the 'is' assertion. > > a is b > and then, do what you want with a (or b), a is b remains True. > > THIS is the meaning of expr1 = expr2, but in computer science, this is not as > important as it is in pure logic (most languages do not even provide the 'is' > assertion). > > -- > _____________ > > Maric Michaud > _____________ > > Aristote - www.aristote.info > 3 place des tapis > 69004 Lyon > Tel: +33 426 880 097 From bencvt at gmail.com Fri Jun 2 00:16:33 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 1 Jun 2006 15:16:33 -0700 Subject: grouping a flat list of number by range In-Reply-To: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> Message-ID: <1149200193.757861.51060@i40g2000cwc.googlegroups.com> joh12005 at yahoo.fr wrote: > i'm looking for a way to have a list of number grouped by consecutive > interval, after a search, for example : > > [3, 6, 7, 8, 12, 13, 15] > > => > > [[3, 4], [6,9], [12, 14], [15, 16]] > > (6, not following 3, so 3 => [3:4] ; 7, 8 following 6 so 6, 7, 8 => > [6:9], and so on) > > i was able to to it without generators/yield but i think it could be > better with them, may be do you an idea? Sure: def group_intervals(it): it = iter(it) val = it.next() run = [val, val+1] for val in it: if val == run[1]: run[1] += 1 else: yield run run = [val, val+1] yield run --Ben From yan at NsOeSiPnAeMr.com Fri Jun 2 00:19:38 2006 From: yan at NsOeSiPnAeMr.com (Captain Dondo) Date: Thu, 01 Jun 2006 15:19:38 -0700 Subject: Replace one element of a tuple (LONG) In-Reply-To: <1149198946.567904.260480@f6g2000cwb.googlegroups.com> References: <127ulhn6h7hvj22@corp.supernews.com> <1149198946.567904.260480@f6g2000cwb.googlegroups.com> Message-ID: <127upu8k63qnu10@corp.supernews.com> BartlebyScrivener wrote: >>>I've looked at various search-and-replace snippets but none that address >>>what I am trying to do.... > > > I think you need to tell more about what you're trying to do. You say > it's in a database? Is that why you can't just put the whole blob in > your text editor and do search-and-replace? > > And is that also why you can't turn it into a giant string and do > giantstring.replace('unwanted','wanted') > > rd > Fair enough. I am trying to pull records from one database (on tooth.seiner.lan) and create a smaller table with only selected elements in another database (on localhost aka hermes). My code so far: import MySQLdb import sys, os, os.path, time, string, dialog masterBackend="tooth.seiner.lan" toGoBackend="hermes.seiner.lan" masterDB=MySQLdb.connect(host=masterBackend,user="mythtv",passwd="mythtv",db="mythconverg") # pull recordings from masterDB c=masterDB.cursor() c.execute("""SELECT title, subtitle, starttime FROM recorded""") # build our dialog checkbox d = dialog.Dialog(dialog="dialog") d.add_persistent_args(["--backtitle", "Myth2Go"]) recordings=[] for listing in c.fetchall(): recordings.append( (listing[0]+'|'+listing[2].isoformat(), listing[1],0)) recordings.sort() (retcode, itemlist) = d.checklist(text="", height=15, width=70, list_height=7, choices=recordings, title="Which recordings do you want to transfer?") selectlist=[] for listing in itemlist: print listing (rectitle, recdate) = listing.split('|',1) c.execute("""SELECT * FROM recorded WHERE title=%s AND starttime=%s""",(rectitle,recdate)) selectlist.append(c.fetchone()) ======================================================== The problem is the last line. I am creating a bunch of tuples that are, for my purposes, incorrect. I would like to create them with masterBackend replaced by toGoBackend. Currently (I corrected a small bug based on another post) after a user selects what recordings s/he wants, selectlist contains: [ (1028L, datetime.datetime(2006, 5, 26, 7, 0), datetime.datetime(2006, 5, 26, 7, 30), 'Arthur', "What's Cooking?; Buster's Special Delivery", '', 'Children', 'tooth.seiner.lan', None, 0L, None, 1L, 1L, 'Default', 9L, 'SH044107', 'EP0441070207', datetime.datetime(2006, 5, 26, 7, 31, 1), 1162899392L, 0.0, 0, datetime.date(2006, 5, 26), 0, 0L, 0), (1028L, datetime.datetime(2006, 5, 27, 9, 0), datetime.datetime(2006, 5, 27, 9, 30), 'Arthur', 'Unfinished; D.W., Bossy Boots', '', 'Children', 'tooth.seiner.lan', None, 0L, None, 1L, 1L, 'Default', 9L, 'SH044107', 'EP0441070204', datetime.datetime(2006, 5, 27, 9, 31, 26), 1164783552L, 0.0, 0, datetime.date(2006, 5, 23), 0, 0L, 0), (1028L, datetime.datetime(2006, 5, 30, 7, 0), datetime.datetime(2006, 5, 30, 7, 30), 'Arthur', 'Prunella Sees the Light; Return of the Snowball', 'Prunella prepares for a sleepover with Marina; D.W. protects a snowball.', 'Children', 'tooth.seiner.lan', None, 0L, None, 1L, 1L, 'Default', 9L, 'SH044107', 'EP0441070123', datetime.datetime(2006, 5, 30, 7, 31, 24), 1164179392L, 0.0, 1, datetime.date(2002, 11, 28), 0, 0L, 0) ] which is the correct format to insert into the new database. What I'd like to do is build the correct selectlist in the first place, rather than build the wrong one and then rebuild a correct one. I can't find a replace method that would work on a tuple (not surprising since they're immutable) but I also can't find a replace function that would replace an element of a tuple and return a new tuple. --Yan From bnblazer at gmail.com Fri Jun 2 00:27:22 2006 From: bnblazer at gmail.com (Brian) Date: 1 Jun 2006 15:27:22 -0700 Subject: TSV to HTML In-Reply-To: <7f5u721mhaauqak62krrb4p9ruhicaus45@4ax.com> References: <1149098823.979329.9220@f6g2000cwb.googlegroups.com> <447e268a$0$3699$4d3efbfe@news.sover.net> <1149126509.984331.306530@h76g2000cwa.googlegroups.com> <1149157775.490474.173970@y43g2000cwc.googlegroups.com> <7f5u721mhaauqak62krrb4p9ruhicaus45@4ax.com> Message-ID: <1149200842.674309.323930@g10g2000cwb.googlegroups.com> Dennis Lee Bieber wrote: > On 1 Jun 2006 03:29:35 -0700, "Brian" declaimed the > following in comp.lang.python: > > > Thank you for that response. Your code was very helpful to me. I > > think that actually seeing how it should be done in Python was a lot > > more educational than spending hours with trial and error. > > > It's not the best code around -- I hacked it together pretty much > line-for-line from an assumption of what the Ruby was doing (I don't do > Ruby -- too much PERL idiom in it) > > > One question (and this is a topic that I still have trouble getting my > > arms around). Why is the text in STYLEBLOCK tripple quoted? > > > Triple quotes allow: 1) use of single quotes within the block > without needing to escape them; 2) allows the string to span multiple > lines. Plain string quoting must be one logical line to the parser. > > I've practically never seen anyone use a line continuation character > in Python. And triple quoting looks cleaner than parser concatenation. > > The alternatives would have been: > > Line Continuation: > STYLEBLOCK = '\n\ > \n\ > ' > Note the \n\ as the end of each line; the \n is to keep the > formatting on the generated HTML (otherwise everything would be one long > line) and the final \ (which must be the physical end of line) > signifying "this line is continued". Also note that I used ' rather than > " to avoid escaping the " on text/css. > > Parser Concatenation: > STYLEBLOCK = ( > '\n" > ) > > Note the use of ( ) where the original had """ """. Also note that > each line has quotes at start/end (the first has ' to avoid escaping > text/css). There are no commas separating each line (and the \n is still > for formatting). Using the ( ) creates an expression, and Python is nice > enough to let one split expressions inside () or [lists], {dicts}, over > multiple lines (I used that feature in a few spots to put call arguments > on multiple lines). Two strings that are next to each other > > "string1" "string2" > > are parsed as one string > > "string1string2" > > Using """ (or ''') is the cleanest of those choices, especially if > you want to do preformatted layout of the text. It works similar to the > Ruby/PERL construct that basically said: Copy all text up to the next > occurrence of MARKER_STRING. Thank you for your explanation, now it makes sense. Brian From bignose+hates-spam at benfinney.id.au Fri Jun 2 00:30:54 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 02 Jun 2006 08:30:54 +1000 Subject: losing handles of open files References: <000c01c68558$a48a9680$0201a8c0@mcuf7> Message-ID: <877j40zext.fsf@benfinney.id.au> Please don't post non-text message bodies to discussion forums. Message bodies should be plain text. "Anthra Norell" writes: > If a piece of code exits with an exception before it closes an open > file, that file seems to remain locked, which is real pain in the > butt You will want to examine the 'finally' clause, which is executed after the 'try' suite regardless of exceptions. You may also be interested in the 'with' statement, coming in Python 2.5, which will be a more natural way of expressing this idiom. -- \ "If nature has made any one thing less susceptible than all | `\ others of exclusive property, it is the action of the thinking | _o__) power called an idea" -- Thomas Jefferson | Ben Finney From jmcmonagle at velseis.com.au Fri Jun 2 00:30:56 2006 From: jmcmonagle at velseis.com.au (John McMonagle) Date: Fri, 02 Jun 2006 08:30:56 +1000 Subject: Tkinter - changing existing Dialog? In-Reply-To: References: Message-ID: <1149201056.26711.27.camel@kuepper.vels-int.com.au> On Thu, 2006-06-01 at 08:31 -0400, Michael Yanowitz wrote: > Hello: > > > I have a Tkinter GUI Dialog with many buttons and labels and text > widgets. > What I would like to do is, can I: > > 1) Disable/deactivate/hide a button, text widget that is already drawn (and > of course the opposite enable/activate/show it)? > > 2) Change the text of a label or button that is already drawn? > > based on actions taken by the user. Can it be done without destroying > the present dialog or the objects in it and creating a new one? > > Sorry for what probably is such a trivial and basic question. I just can't > find the answer or know what the technical term for what I want to do is to > search for it myself. To disable/deactivate a button widget, use the keyword 'state'. For example, import Tkinter as Tk root = Tk.Tk() bid = Tk.Button(root, text='test', state=Tk.NORMAL) bid.pack() bid.configure(state=Tk.DISABLED) If you want to hide the button (using Pack geometry manager): bid.pack_forget() You can pack it again using bid.pack() but it may be difficult to pack it back where you originally intended. If you are using the Grid geometry manager: bid.grid_forget() To put it back simply call grid again with the same row, column. Changing the text of a label or button already drawn is simply done by a call to the configure method on the button or label's text attribute: bid.configure(text='Help') Regards, John -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. From bencvt at gmail.com Fri Jun 2 00:33:38 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 1 Jun 2006 15:33:38 -0700 Subject: argmax In-Reply-To: References: Message-ID: <1149201218.659046.64030@u72g2000cwu.googlegroups.com> David Isaac wrote: > 2. Is this a good argmax (as long as I know the iterable is finite)? > def argmax(iterable): return max(izip( iterable, count() ))[1] Other than the subtle difference that Peter Otten pointed out, that's a good method. However if the iterable is a list, it's cleaner (and more efficient) to use seq.index(max(seq)). That way you won't be creating and comparing all those tuples. def argmax(it): try: it.index except AttributeError: it = list(it) # Or if it would too expensive to convert it to list: #return -max((v, -i) for i, v in enumerate(it))[1] return it.index(max(it)) --Ben From paddy3118 at netscape.net Fri Jun 2 00:36:56 2006 From: paddy3118 at netscape.net (Paddy) Date: 1 Jun 2006 15:36:56 -0700 Subject: grouping a flat list of number by range References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> Message-ID: <1149201416.196975.123370@c74g2000cwc.googlegroups.com> joh12005 at yahoo.fr wrote: > hello, > > i'm looking for a way to have a list of number grouped by consecutive > interval, after a search, for example : > > [3, 6, 7, 8, 12, 13, 15] > > => > > [[3, 4], [6,9], [12, 14], [15, 16]] > > (6, not following 3, so 3 => [3:4] ; 7, 8 following 6 so 6, 7, 8 => > [6:9], and so on) > > i was able to to it without generators/yield but i think it could be > better with them, may be do you an idea? > > best regards, > > J. I did a proceedural version, then re-read your post and did a generator based version ;-) === interv1 === >>> inlist = [3, 6, 7, 8, 12, 13, 15] >>> tmp = [] >>> for i,val in enumerate(inlist): ... if i==0: ... tmp.append(val) ... elif val != valinc: ... tmp += [valinc, val] ... valinc = val+1 ... >>> tmp.append(valinc) >>> tmp [3, 4, 6, 9, 12, 14, 15, 16] >>> tmp[0::2] [3, 6, 12, 15] >>> tmp[1::2] [4, 9, 14, 16] >>> zip(tmp[0::2], tmp[1::2]) [(3, 4), (6, 9), (12, 14), (15, 16)] >>> === END interv1 === === interv2 === >>> def interv2(inlist): ... for i,val in enumerate(inlist): ... if i==0: ... tmp = val ... elif val != valinc: ... yield [tmp, valinc] ... tmp = val ... valinc = val+1 ... yield [tmp, valinc] ... >>> list(interv2(inlist)) [[3, 4], [6, 9], [12, 14], [15, 16]] === END interv2 === - Paddy. From slawomir.nowaczyk.847 at student.lu.se Fri Jun 2 00:40:47 2006 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Fri, 02 Jun 2006 00:40:47 +0200 Subject: An oddity in list comparison and element assignment In-Reply-To: <1149199942.955228.281950@u72g2000cwu.googlegroups.com> References: <1149199942.955228.281950@u72g2000cwu.googlegroups.com> Message-ID: <20060602002705.FC33.SLAWOMIR.NOWACZYK.847@student.lu.se> On Thu, 01 Jun 2006 15:12:23 -0700 michael.f.ellis at gmail.com wrote: #> I believe that 'is' tests equality of reference, such that #> #> >>> a = range(1,3) #> >>> b = range(1,3) #> >>> a is b #> False #> #> The 'is' operator tells you whether a and b refer to the same object. #> What I've been discussing is whether == should test for "structural" #> equality so that a and b remain equivalent under parallel mutations #> (and also under single mutations to common references) What does "parallel mutations" mean? In particular, what should be the results of each of the following three comparisons: x, y, z = [1],[1],[1] a, b = [x,y], [y,z] c, d = [[1],[1]], [[1],[1]] a == b c == d a[0].remove(1) b[0].remove(1) a == b So, do I understand correctly that you would like first comparison (a==b) to return "False" and second comparison (c==d) to return "True"? -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) Living on Earth may be expensive, but it includes an annual free trip around the Sun. From jerry.levan at gmail.com Fri Jun 2 00:40:59 2006 From: jerry.levan at gmail.com (jerry.levan at gmail.com) Date: 1 Jun 2006 15:40:59 -0700 Subject: Solved: Tktable, WinXP and ActiveState Python 2.4.3,x References: <1149047353.883167.18100@i39g2000cwa.googlegroups.com> Message-ID: <1149201659.936164.68960@y43g2000cwc.googlegroups.com> jerry.levan at gmail.com wrote: > Hi, > I have a python app that runs fine on MacOS X and Fedora Core 5. > > This evening I dragged the folder over to my windows partition and > tried to run the rascal. > > The program starts up fine but at the first call to create a Table > object > I get > > 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:\Documents and > Settings\Jerry\Desktop\PyPgBrowseUni\PyPgExplorer.py", line 7, in ? > obj.main() > File "C:\Documents and > Settings\Jerry\Desktop\PyPgBrowseUni\Resources\PyPgBrowse.py", line 72, > in main > self.build_ui( info) > File "C:\Documents and > Settings\Jerry\Desktop\PyPgBrowseUni\Resources\PyPgBrowse.py", line > 187, in build_ui > rowtagcommand=self.rowproc > File "C:\Documents and > Settings\Jerry\Desktop\PyPgBrowseUni\Resources\Tktable.py", line 64, in > __init__ > master.tk.call('load', '', 'Tktable' ) > TclError: package "Tktable" isn't loaded statically > : > > I get the same error if I try to create a Table object from the command > line > in a console. > > I tried waving a dead chicken at my laptop but it did no good. > > Is there some special magic to get Tktable.py to play nice? > I do have the latest Tcl from Active State loaded on my box and > the Tktable in my Tk programs work well... > > Thanks for any insight.... > > Jerry Thanks to the good folks at Active State here is a way to use tktable from Python. 1) Put the wrapper file Tktable.py into C:\Python24\Lib\lib-tk 2) Copy the whole folder C:\Tcl\lib\Tktable* to C:\Python\tcl Letter Rip.... Thanks Jeff... Jerry From sjmachin at lexicon.net Fri Jun 2 00:51:16 2006 From: sjmachin at lexicon.net (John Machin) Date: Fri, 02 Jun 2006 08:51:16 +1000 Subject: struct: type registration? In-Reply-To: <1149185926.636174.48970@y43g2000cwc.googlegroups.com> References: <447e4b98$1@news.eftel.com> <1149185926.636174.48970@y43g2000cwc.googlegroups.com> Message-ID: <447F6F64.400@lexicon.net> On 2/06/2006 4:18 AM, Serge Orlov wrote: > Giovanni Bajo wrote: >> John Machin wrote: >>> I am an idiot, so please be gentle with me: I don't understand why you >>> are using struct.pack at all: >> Because I want to be able to parse largest chunks of binary datas with custom >> formatting. Did you miss the whole point of my message: >> >> struct.unpack("3liiSiiShh", data) > > Did you want to write struct.unpack("Sheesh", data) ? Seriously, the > main problem of struct is that it uses ad-hoc abbreviations for > relatively rarely[1] used functions calls and that makes it hard to > read. Indeed. The first time I saw something like struct.pack('20H', ...) I thought it was a FORTRAN format statement :-) > > If you want to parse binary data use pyconstruct > > Looks promising on the legibility and functionality fronts. Can you make any comment on the speed? Reason for asking is that Microsoft Excel files have this weird "RK" format for expressing common float values in 32 bits (refer http://sc.openoffice.org, see under "Documentation" heading). I wrote and support the xlrd module (see http://cheeseshop.python.org/pypi/xlrd) for reading those files in portable pure Python. Below is a function that would plug straight in as an example of Giovanni's custom unpacker functions. Some of the files can be very large, and reading rather slow. Cheers, John from struct import unpack def unpack_RK(rk_str): # arg is 4 bytes flags = ord(rk_str[0]) if flags & 2: # There's a SIGNED 30-bit integer in there! i, = unpack('>= 2 # div by 4 to drop the 2 flag bits if flags & 1: return i / 100.0 return float(i) else: # It's the most significant 30 bits # of an IEEE 754 64-bit FP number d, = unpack(' <1149201416.196975.123370@c74g2000cwc.googlegroups.com> Message-ID: <1149202388.135494.148890@u72g2000cwu.googlegroups.com> I did a little re-arranging of the generator version: def interv3(inlist): tmp = inlist[0] valinc = tmp+1 for val in inlist[1:]: if val != valinc: yield [tmp, valinc]; tmp = val valinc = val+1 yield [tmp, valinc] From almondb at gmail.com Fri Jun 2 00:53:37 2006 From: almondb at gmail.com (Brian) Date: 1 Jun 2006 15:53:37 -0700 Subject: Replace one element of a tuple (LONG) In-Reply-To: <127upu8k63qnu10@corp.supernews.com> References: <127ulhn6h7hvj22@corp.supernews.com> <1149198946.567904.260480@f6g2000cwb.googlegroups.com> <127upu8k63qnu10@corp.supernews.com> Message-ID: <1149202416.959127.71620@i39g2000cwa.googlegroups.com> Captain Dondo wrote: > What I'd like to do is build the correct selectlist in the first place, > rather than build the wrong one and then rebuild a correct one. This is sounding more like a SQL/DB problem and less like a Python one. If you have a field that is being pulled from the database that you would like to do a substitution on, I'm fairly sure MySQL includes a CASE statement in their flavor of SQL. Instead of performing a SELECT * in your script you could select the individual fields you want, and instead of just pulling the problematic column as is, you could pull it as something like "select case when sourcehost = x then y else sourcehost end case, ...". Naturally if an entire column needs to be replaced with a static value, you won't even need to use CASE. HTH From jes at nl.demon.net Fri Jun 2 00:53:43 2006 From: jes at nl.demon.net (Jim Segrave) Date: Thu, 01 Jun 2006 22:53:43 -0000 Subject: grouping a flat list of number by range References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> <1149201416.196975.123370@c74g2000cwc.googlegroups.com> Message-ID: <127urvnrbvjgr07@corp.supernews.com> In article <1149201416.196975.123370 at c74g2000cwc.googlegroups.com>, Paddy wrote: >=== interv2 === >>>> def interv2(inlist): >... for i,val in enumerate(inlist): >... if i==0: >... tmp = val >... elif val != valinc: >... yield [tmp, valinc] >... tmp = val >... valinc = val+1 >... yield [tmp, valinc] >... >>>> list(interv2(inlist)) >[[3, 4], [6, 9], [12, 14], [15, 16]] > >=== END interv2 === This doesn't actually run, changing it to make it do so: def interv2(inlist): tmp = valinc = 0 for i,val in enumerate(inlist): if i==0: tmp = val valinc = val + 1 elif val != valinc: yield [tmp, valinc] tmp = val valinc = val+1 yield [tmp, valinc] it now works, but returns [0, 0] when passed an empty list, when it should return nothing at all -- Jim Segrave (jes at jes-2.demon.nl) From paddy3118 at netscape.net Fri Jun 2 00:59:40 2006 From: paddy3118 at netscape.net (Paddy) Date: 1 Jun 2006 15:59:40 -0700 Subject: grouping a flat list of number by range In-Reply-To: <127urvnrbvjgr07@corp.supernews.com> References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> <1149201416.196975.123370@c74g2000cwc.googlegroups.com> <127urvnrbvjgr07@corp.supernews.com> Message-ID: <1149202780.780252.242110@f6g2000cwb.googlegroups.com> Jim Segrave wrote: > In article <1149201416.196975.123370 at c74g2000cwc.googlegroups.com>, > Paddy wrote: > >=== interv2 === > >>>> def interv2(inlist): > >... for i,val in enumerate(inlist): > >... if i==0: > >... tmp = val > >... elif val != valinc: > >... yield [tmp, valinc] > >... tmp = val > >... valinc = val+1 > >... yield [tmp, valinc] > >... > >>>> list(interv2(inlist)) > >[[3, 4], [6, 9], [12, 14], [15, 16]] > > > >=== END interv2 === > > This doesn't actually run, changing it to make it do so: > > def interv2(inlist): > tmp = valinc = 0 > for i,val in enumerate(inlist): > if i==0: > tmp = val > valinc = val + 1 > elif val != valinc: > yield [tmp, valinc] > tmp = val > valinc = val+1 > yield [tmp, valinc] > > it now works, but returns [0, 0] when passed an empty list, when it > should return nothing at all > -- > Jim Segrave (jes at jes-2.demon.nl) Jim, I had tabs/spaces indent problems when cut-n-pasting. What I ran was more like the version below, but i did a quick separation of the line that has the ';' in it and goofed. >>> def interv2(inlist): ... for i,val in enumerate(inlist): ... if i==0: ... tmp = val ... elif val != valinc: ... yield [tmp, valinc]; tmp = val ... valinc = val+1 ... yield [tmp, valinc] ... >>> list(interv2(inlist)) [[3, 4], [6, 9], [12, 14], [15, 16]] From bdesth.quelquechose at free.quelquepart.fr Fri Jun 2 04:25:54 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 02 Jun 2006 04:25:54 +0200 Subject: if not CGI: In-Reply-To: References: Message-ID: <447f722b$0$30312$626a54ce@news.free.fr> Max a ?crit : (snip) > But now I'm ready to do it in the real world. Nothing complicated, but a > real project. And I have to choose my tools. Zope, Plone, Django, what > are these? Zope -> an application server Plone -> a CMS built upon Zope Django -> a MVC fullstack framework (fullstack : integration with a server + ORM + template system + various utilities). > I don't have to stick with Python, although it's my preferred > language. I know Python, Java and C++. But I'm ready to learn Ruby if > RoR is as good as they say. RoR is not bad, but really over-hyped. There's no shortage of at least as good solutions in Python. You may want to look at Django, Turbogears, Pylons, web.py etc. for fullstack MVC frameworks. There are more barebones solutions, like CherryPy (the application server Turbogears is built upon), Myghty (extended perl::Mason port, used by Pylons), mod_python (if you're an hard-core Apache fanatic), WebStack (if you want to deploy on almost any server), and some other pieces like formencode (form validation), SQLObject (ORM, used by Turbogears and Pylons), SQLAlchemy (another ORM, very promising, by the author of Myghty), Routes (port of RoR routes, used by Pylons) and a lot of templating systems. So you can even build your own fullstack framework from existing pieces (that's what Turbogears and Pylons are doing FWIW). And also whole lot of more specific solutions : Albatross, Quixote, Karrigel, Twisted/nevow, (...), and of course Zope 2.x and 3.x, but it may be overkill and long to learn. Also, FWIW, Trac is almost a usable (somewhat minimalist) framework on it's own. So the problem is not "are there good solutions", but "which one to choose" !-) The answer of course depends on what you want and what you like, but taking a few days to play with Turbogears, Django and Pylons might be a good idea. > I could do it in Python cgi (or mod_python). But it seems from all the > hype that this is not a good way to write scaleable, extensible web > applications. Trac is a perfect counter-example IMHO. From yan at NsOeSiPnAeMr.com Fri Jun 2 01:08:43 2006 From: yan at NsOeSiPnAeMr.com (Captain Dondo) Date: Thu, 01 Jun 2006 16:08:43 -0700 Subject: Replace one element of a tuple (LONG) In-Reply-To: <1149202416.959127.71620@i39g2000cwa.googlegroups.com> References: <127ulhn6h7hvj22@corp.supernews.com> <1149198946.567904.260480@f6g2000cwb.googlegroups.com> <127upu8k63qnu10@corp.supernews.com> <1149202416.959127.71620@i39g2000cwa.googlegroups.com> Message-ID: <127usq9lrqavm3d@corp.supernews.com> Brian wrote: > Captain Dondo wrote: > >>What I'd like to do is build the correct selectlist in the first place, >>rather than build the wrong one and then rebuild a correct one. > > > This is sounding more like a SQL/DB problem and less like a Python one. > If you have a field that is being pulled from the database that you > would like to do a substitution on, I'm fairly sure MySQL includes a > CASE statement in their flavor of SQL. Instead of performing a SELECT > * in your script you could select the individual fields you want, and > instead of just pulling the problematic column as is, you could pull it > as something like "select case when sourcehost = x then y else > sourcehost end case, ...". Naturally if an entire column needs to be > replaced with a static value, you won't even need to use CASE. > AFAICT, that one column is always the same, the name of the host that the database resides on. As myth can use multiple backends , it sort of makes sense, but it seems redunandant to me. Even with mutliple backends, I would hope you have a single database.... I thought about just picking all the other fields via the SQL query, but this seemed simpler to me.... Anyway, here's the code I came up with: for listing in itemlist: (rectitle, recdate) = listing.split('|',1) c.execute("""SELECT * FROM recorded WHERE title=%s AND starttime=%s""",(rectitle,recdate)) for listitem in c.fetchall(): if 'tooth.seiner.lan' in listitem: selectlist.append(listitem[:7] + ('hermes.seiner.lan',) + listitem[9:]) else: selectlist.append(listitem) From jes at nl.demon.net Fri Jun 2 01:13:44 2006 From: jes at nl.demon.net (Jim Segrave) Date: Thu, 01 Jun 2006 23:13:44 -0000 Subject: grouping a flat list of number by range References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> <1149201416.196975.123370@c74g2000cwc.googlegroups.com> <1149202388.135494.148890@u72g2000cwu.googlegroups.com> Message-ID: <127ut58e8q0ok5a@corp.supernews.com> In article <1149202388.135494.148890 at u72g2000cwu.googlegroups.com>, Paddy wrote: >I did a little re-arranging of the generator version: > >def interv3(inlist): > tmp = inlist[0] > valinc = tmp+1 > for val in inlist[1:]: > if val != valinc: > yield [tmp, valinc]; > tmp = val > valinc = val+1 > yield [tmp, valinc] Still fails when passed an empty list, the initial assignment to tmp is an IndexError -- Jim Segrave (jes at jes-2.demon.nl) From jes at nl.demon.net Fri Jun 2 01:15:17 2006 From: jes at nl.demon.net (Jim Segrave) Date: Thu, 01 Jun 2006 23:15:17 -0000 Subject: grouping a flat list of number by range References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> <1149201416.196975.123370@c74g2000cwc.googlegroups.com> <127urvnrbvjgr07@corp.supernews.com> <1149202780.780252.242110@f6g2000cwb.googlegroups.com> Message-ID: <127ut85lpcmoa5b@corp.supernews.com> In article <1149202780.780252.242110 at f6g2000cwb.googlegroups.com>, Paddy wrote: > >What I ran was more like the version below, but i did a quick >separation of the line that has the ';' in it and goofed. > >>>> def interv2(inlist): >... for i,val in enumerate(inlist): >... if i==0: >... tmp = val >... elif val != valinc: >... yield [tmp, valinc]; tmp = val >... valinc = val+1 >... yield [tmp, valinc] >... >>>> list(interv2(inlist)) >[[3, 4], [6, 9], [12, 14], [15, 16]] Fails on an empty list, as tmp is not defined when it hits the yield -- Jim Segrave (jes at jes-2.demon.nl) From alanalan at newsgroup.nospam Fri Jun 2 01:04:10 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 1 Jun 2006 19:04:10 -0400 Subject: Conditional Expressions in Python 2.4 Message-ID: Hi, I am using Python 2.4. I read the PEP 308 at: http://www.python.org/dev/peps/pep-0308/ I tried the statement: a= "Yes" if 1==1 else "No" but the interpreter doesn't accept it. Do we have the conditional expressions in Python 2.4? Thank you, Alan From reply.in.the.newsgroup at my.address.is.invalid Fri Jun 2 01:18:29 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Fri, 02 Jun 2006 01:18:29 +0200 Subject: Zope / Plone Groups References: <1149178209.825191.128050@c74g2000cwc.googlegroups.com> Message-ID: d.schulz81 at gmx.net: >are there any specific groups for zope / plone regarding questions? Try plone-users: http://plone.org/support -- Ren? Pijlman From alanalan at newsgroup.nospam Fri Jun 2 01:08:04 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 1 Jun 2006 19:08:04 -0400 Subject: Can Python format long integer 123456789 to 12,3456,789 ? Message-ID: <8oKfg.1621$Su3.139425@news20.bellglobal.com> Hi, Is there any built in feature in Python that can format long integer 123456789 to 12,3456,789 ? Thank you, Alan From robert.kern at gmail.com Fri Jun 2 01:24:29 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 01 Jun 2006 18:24:29 -0500 Subject: Conditional Expressions in Python 2.4 In-Reply-To: References: Message-ID: A.M wrote: > Do we have the conditional expressions in Python 2.4? No. -- 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 JKolstad71HatesSpam at yahoo.com Fri Jun 2 01:27:22 2006 From: JKolstad71HatesSpam at yahoo.com (Joel Kolstad) Date: Thu, 1 Jun 2006 16:27:22 -0700 Subject: Recommendations for CD/DVD-based or on-line Python classes? Message-ID: <127uturbd73g5ca@corp.supernews.com> Just curious... I have plenty of programming background (C++ being the closest to Python), and I have a copy of Lutz's "Learning Python," but before I dive head-first into that tome, does anyone know of a web-based or CD/DVD-based training class that's priced for individuals? Example of what I'm looking for: Something like 6 or 7 years ago Ziff-Davis had a bunch of on-line instructor-lead courses, where you'd read a chapter in a book, read the instructor's take on the chapter (just a few pages), perform the programming assignments, and ask the instructor if you had any difficulties. There was a solid schedule (ch. 1 this week, ch. 2 the next, etc. -- courses repeated every quarter or somesuch) as well. Ziff-Davis charged something like $99 or $199/year for this service (all the courses you wanted to sign up for -- quite reasonable, IMO) and also made money by requiring the use of their own books (which were often someone else's book that they'd just put their own name on) -- which were usually cheap enough at something like $30/ea. That whole setup worked quite well for me... anyone know of something similar? If not I probably will have to force myself to spend an hour a day or something going through Lutz's book... Thanks, ---Joel Kolstad From rpdooling at gmail.com Fri Jun 2 01:27:25 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 1 Jun 2006 16:27:25 -0700 Subject: Replace one element of a tuple (LONG) In-Reply-To: <127usq9lrqavm3d@corp.supernews.com> References: <127ulhn6h7hvj22@corp.supernews.com> <1149198946.567904.260480@f6g2000cwb.googlegroups.com> <127upu8k63qnu10@corp.supernews.com> <1149202416.959127.71620@i39g2000cwa.googlegroups.com> <127usq9lrqavm3d@corp.supernews.com> Message-ID: <1149204445.622897.26390@c74g2000cwc.googlegroups.com> >> that one column is always the same, the name of the host that >> the database resides on. Then why are you pulling all of the other stuff out of the db? Why don't you just UPDATE tablename SET hostname(or colname) = 'localhost' WHERE search condition = the rows you want to change From yan at NsOeSiPnAeMr.com Fri Jun 2 01:32:45 2006 From: yan at NsOeSiPnAeMr.com (Captain Dondo) Date: Thu, 01 Jun 2006 16:32:45 -0700 Subject: Replace one element of a tuple (LONG) In-Reply-To: <1149204445.622897.26390@c74g2000cwc.googlegroups.com> References: <127ulhn6h7hvj22@corp.supernews.com> <1149198946.567904.260480@f6g2000cwb.googlegroups.com> <127upu8k63qnu10@corp.supernews.com> <1149202416.959127.71620@i39g2000cwa.googlegroups.com> <127usq9lrqavm3d@corp.supernews.com> <1149204445.622897.26390@c74g2000cwc.googlegroups.com> Message-ID: <127uu7c9c1s9n8e@corp.supernews.com> BartlebyScrivener wrote: >>>that one column is always the same, the name of the host that >>>the database resides on. > > > Then why are you pulling all of the other stuff out of the db? Why > don't you just > > UPDATE tablename > SET hostname(or colname) = 'localhost' > WHERE search condition = the rows you want to change > Well, there is an interactive dialog where the user picks which records s/he wants to put into the other database. So in the target database, that table may not even exist until the user selects which records go in there. But it does sound like I need to do some work on the database query.... :-) --Yan From sjmachin at lexicon.net Fri Jun 2 01:35:37 2006 From: sjmachin at lexicon.net (John Machin) Date: Fri, 02 Jun 2006 09:35:37 +1000 Subject: grouping a flat list of number by range In-Reply-To: <1149201416.196975.123370@c74g2000cwc.googlegroups.com> References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> <1149201416.196975.123370@c74g2000cwc.googlegroups.com> Message-ID: <447F79C9.6080407@lexicon.net> On 2/06/2006 8:36 AM, Paddy wrote: > joh12005 at yahoo.fr wrote: >> hello, >> >> i'm looking for a way to have a list of number grouped by consecutive >> interval, after a search, for example : >> >> [3, 6, 7, 8, 12, 13, 15] >> >> => >> >> [[3, 4], [6,9], [12, 14], [15, 16]] >> >> (6, not following 3, so 3 => [3:4] ; 7, 8 following 6 so 6, 7, 8 => >> [6:9], and so on) >> >> i was able to to it without generators/yield but i think it could be >> better with them, may be do you an idea? >> >> best regards, >> >> J. > > I did a proceedural version, then re-read your post and did a generator > based version ;-) > > === interv1 === >>>> inlist = [3, 6, 7, 8, 12, 13, 15] >>>> tmp = [] >>>> for i,val in enumerate(inlist): > ... if i==0: > ... tmp.append(val) > ... elif val != valinc: > ... tmp += [valinc, val] > ... valinc = val+1 > ... >>>> tmp.append(valinc) >>>> tmp > [3, 4, 6, 9, 12, 14, 15, 16] >>>> tmp[0::2] > [3, 6, 12, 15] >>>> tmp[1::2] > [4, 9, 14, 16] >>>> zip(tmp[0::2], tmp[1::2]) > [(3, 4), (6, 9), (12, 14), (15, 16)] > > === END interv1 === > > === interv2 === >>>> def interv2(inlist): > ... for i,val in enumerate(inlist): > ... if i==0: > ... tmp = val > ... elif val != valinc: > ... yield [tmp, valinc] > ... tmp = val > ... valinc = val+1 > ... yield [tmp, valinc] > ... >>>> list(interv2(inlist)) > [[3, 4], [6, 9], [12, 14], [15, 16]] > > === END interv2 === > > - Paddy. > Oh the siren call of every new feature in the language! enumerate() just to get a first-time test, and then botch it?? Read the following; the replacement version uses a simple old-fashioned inelegant flag, works with an empty sequence, and doesn't depend on the input being sliceable or indexable. HTH, John C:\junk>type interval.py def interv2(inlist): for i,val in enumerate(inlist): if i==0: tmp = val elif val != valinc: yield [tmp, valinc] tmp = val valinc = val+1 yield [tmp, valinc] def interv3(inseq): first = True for val in inseq: if first: tmp = val first = False elif val != valinc: yield [tmp, valinc] tmp = val valinc = val + 1 if not first: yield [tmp, valinc] tests = [ [3, 4, 6, 9, 12, 14, 15, 16], [3, 3, 3], [], ] for func in (interv3, interv2): for test in tests: print "%s(%s) ->" % (func.__name__, test) result = list(func(test)) print "\t%r" % result C:\junk>interval.py interv3([3, 4, 6, 9, 12, 14, 15, 16]) -> [[3, 5], [6, 7], [9, 10], [12, 13], [14, 17]] interv3([3, 3, 3]) -> [[3, 4], [3, 4], [3, 4]] interv3([]) -> [] interv2([3, 4, 6, 9, 12, 14, 15, 16]) -> [[3, 5], [6, 7], [9, 10], [12, 13], [14, 17]] interv2([3, 3, 3]) -> [[3, 4], [3, 4], [3, 4]] interv2([]) -> Traceback (most recent call last): File "C:\junk\interval.py", line 33, in ? result = list(func(test)) File "C:\junk\interval.py", line 9, in interv2 yield [tmp, valinc] UnboundLocalError: local variable 'tmp' referenced before assignment C:\junk> From scott.daniels at acm.org Fri Jun 2 01:49:32 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 01 Jun 2006 16:49:32 -0700 Subject: Recommendations for CD/DVD-based or on-line Python classes? In-Reply-To: <127uturbd73g5ca@corp.supernews.com> References: <127uturbd73g5ca@corp.supernews.com> Message-ID: <447f78a4$1@nntp0.pdx.net> Joel Kolstad wrote: > Just curious... I have plenty of programming background (C++ being the closest > to Python), and I have a copy of Lutz's "Learning Python," but before I dive > head-first into that tome, does anyone know of a web-based or CD/DVD-based > training class that's priced for individuals? > > Example of what I'm looking for: Something like 6 or 7 years ago Ziff-Davis > had a bunch of on-line instructor-lead courses, where you'd read a chapter in > a book, read the instructor's take on the chapter (just a few pages), perform > the programming assignments, and ask the instructor if you had any > difficulties. There was a solid schedule (ch. 1 this week, ch. 2 the next, > etc. -- courses repeated every quarter or somesuch) as well. Ziff-Davis > charged something like $99 or $199/year for this service (all the courses you > wanted to sign up for -- quite reasonable, IMO) and also made money by > requiring the use of their own books (which were often someone else's book > that they'd just put their own name on) -- which were usually cheap enough at > something like $30/ea. > > That whole setup worked quite well for me... anyone know of something similar? > If not I probably will have to force myself to spend an hour a day or > something going through Lutz's book... > > Thanks, > ---Joel Kolstad > > Well, you could read through all the web thingies around (the online tutorial is great), many others listed "getting started" should help, and to really build your muscles, try the "Python challenge." -- --Scott David Daniels scott.daniels at acm.org From sjmachin at lexicon.net Fri Jun 2 01:58:59 2006 From: sjmachin at lexicon.net (John Machin) Date: Fri, 02 Jun 2006 09:58:59 +1000 Subject: Can Python format long integer 123456789 to 12,3456,789 ? In-Reply-To: <8oKfg.1621$Su3.139425@news20.bellglobal.com> References: <8oKfg.1621$Su3.139425@news20.bellglobal.com> Message-ID: <447f7f43$1@news.eftel.com> On 2/06/2006 9:08 AM, A.M wrote: > Hi, > > Is there any built in feature in Python that can format long integer > 123456789 to 12,3456,789 ? > > Thank you, > Alan Not that I know of, but this little kludge may help: 8<--- import re subber = re.compile(r'^(-?\d+)(\d{3})').sub def fmt_thousands(amt, sep): if amt in ('', '-'): return '' repl = r'\1' + sep + r'\2' while True: new_amt = subber(repl, amt) if new_amt == amt: return amt amt = new_amt if __name__ == "__main__": for prefix in ['', '-']: for k in range(11): arg = prefix + "1234567890.1234"[k:] print "<%s> <%s>" % (arg, fmt_thousands(arg, ",")) 8<--- HTH, John From sjmachin at lexicon.net Fri Jun 2 02:04:45 2006 From: sjmachin at lexicon.net (John Machin) Date: 1 Jun 2006 17:04:45 -0700 Subject: New to Python: Do we have the concept of Hash in Python? In-Reply-To: References: Message-ID: <1149206685.768210.71990@i39g2000cwa.googlegroups.com> A.M wrote: > The application is not mission critical system. It is just a simple > reporting tool. Famous last words. From sjmachin at lexicon.net Fri Jun 2 02:10:47 2006 From: sjmachin at lexicon.net (John Machin) Date: 1 Jun 2006 17:10:47 -0700 Subject: Can Python format long integer 123456789 to 12,3456,789 ? In-Reply-To: <8oKfg.1621$Su3.139425@news20.bellglobal.com> References: <8oKfg.1621$Su3.139425@news20.bellglobal.com> Message-ID: <1149207047.692374.114300@h76g2000cwa.googlegroups.com> A.M wrote: > Hi, > > Is there any built in feature in Python that can format long integer > 123456789 to 12,3456,789 ? > Sorry about my previous post. It would produce 123,456,789. "12,3456,789" is weird -- whose idea PHB or yours?? From bencvt at gmail.com Fri Jun 2 02:11:16 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 1 Jun 2006 17:11:16 -0700 Subject: Can Python format long integer 123456789 to 12,3456,789 ? References: <8oKfg.1621$Su3.139425@news20.bellglobal.com> Message-ID: <1149207075.954869.100130@i39g2000cwa.googlegroups.com> A.M wrote: > Is there any built in feature in Python that can format long integer > 123456789 to 12,3456,789 ? The locale module can help you here: >>> import locale >>> locale.setlocale(locale.LC_ALL, '') 'English_United States.1252' >>> locale.format('%d', 123456789, True) '123,456,789' Be sure to read the caveats for setlocale in the module docs: http://docs.python.org/lib/node323.html I'd recommend calling setlocale only once, and always at the start of your program. --Ben From james.wondrasek at gmail.com Fri Jun 2 02:13:47 2006 From: james.wondrasek at gmail.com (james.wondrasek at gmail.com) Date: 1 Jun 2006 17:13:47 -0700 Subject: Can Python format long integer 123456789 to 12,3456,789 ? References: <8oKfg.1621$Su3.139425@news20.bellglobal.com> Message-ID: <1149207227.173231.126990@h76g2000cwa.googlegroups.com> A.M wrote: > Hi, > > Is there any built in feature in Python that can format long integer > 123456789 to 12,3456,789 ? > > Thank you, > Alan I did this for putting commas into monetary amounts (thus the .2f): def commas(value): return "".join(commafy("%.2f" % value)) def commafy(s): pieces = s.split(".") l = len(pieces[0]) for i in range(0,l): if (l - i) % 3 or not i: yield pieces[0][i] else: yield "," yield pieces[0][i] if len(pieces) > 1: yield "." + pieces[1] jtm From bencvt at gmail.com Fri Jun 2 02:15:59 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 1 Jun 2006 17:15:59 -0700 Subject: Can Python format long integer 123456789 to 12,3456,789 ? In-Reply-To: <1149207047.692374.114300@h76g2000cwa.googlegroups.com> References: <8oKfg.1621$Su3.139425@news20.bellglobal.com> <1149207047.692374.114300@h76g2000cwa.googlegroups.com> Message-ID: <1149207358.977942.245060@c74g2000cwc.googlegroups.com> John Machin wrote: > A.M wrote: > > Hi, > > > > Is there any built in feature in Python that can format long integer > > 123456789 to 12,3456,789 ? > > > > Sorry about my previous post. It would produce 123,456,789. > "12,3456,789" is weird -- whose idea PHB or yours?? If it's not a typo, it's probably a regional thing. See, e.g., http://en.wikipedia.org/wiki/Indian_numbering_system --Ben From overly.crazy.steve at gmail.com Fri Jun 2 02:30:30 2006 From: overly.crazy.steve at gmail.com (overly.crazy.steve at gmail.com) Date: 1 Jun 2006 17:30:30 -0700 Subject: execfile then import back Message-ID: <1149208230.216141.5400@f6g2000cwb.googlegroups.com> I am seeing something strange with execfile. I've simplified the code to: ########## t.py ########## print "here" v = None def f(): global v v = 6 if __name__ == "__main__": f() print "0:", v execfile("x.py") print "0:", v execfile("y.py") print "0:", v ########## x.py and y.py (they are identical) ########## import testexec print "1:", v, testexec.v testexec.v = 7 Runing "python t.py" (with Python 2.4.2), the printout I got is: here 0: 6 here 1: 6 None 0: 6 1: 6 7 0: 6 So there is apparently 2 different instances of v at run time. Can someone please explain (1) why this is the case, and (2) assuming this is correct behavior, how I can avoid this? Thanks. From overly.crazy.steve at gmail.com Fri Jun 2 02:35:03 2006 From: overly.crazy.steve at gmail.com (overly.crazy.steve at gmail.com) Date: 1 Jun 2006 17:35:03 -0700 Subject: execfile then import back In-Reply-To: <1149208230.216141.5400@f6g2000cwb.googlegroups.com> References: <1149208230.216141.5400@f6g2000cwb.googlegroups.com> Message-ID: <1149208503.207296.204200@i39g2000cwa.googlegroups.com> > ########## x.py and y.py (they are identical) ########## > import testexec > print "1:", v, testexec.v > testexec.v = 7 Oops, testexec should be changed to t instead. That is: ########## x.py and y.py (they are identical) ########## import t print "1:", v, t.v t.v = 7 From sjmachin at lexicon.net Fri Jun 2 02:40:35 2006 From: sjmachin at lexicon.net (John Machin) Date: 1 Jun 2006 17:40:35 -0700 Subject: Can Python format long integer 123456789 to 12,3456,789 ? In-Reply-To: <1149207227.173231.126990@h76g2000cwa.googlegroups.com> References: <8oKfg.1621$Su3.139425@news20.bellglobal.com> <1149207227.173231.126990@h76g2000cwa.googlegroups.com> Message-ID: <1149208835.496934.303730@u72g2000cwu.googlegroups.com> james.wondrasek at gmail.com wrote: > A.M wrote: > > Hi, > > > > Is there any built in feature in Python that can format long integer > > 123456789 to 12,3456,789 ? > > > > Thank you, > > Alan > > I did this for putting commas into monetary amounts (thus the .2f): > > def commas(value): > return "".join(commafy("%.2f" % value)) > > def commafy(s): > pieces = s.split(".") > l = len(pieces[0]) > for i in range(0,l): > if (l - i) % 3 or not i: > yield pieces[0][i] > else: > yield "," > yield pieces[0][i] > if len(pieces) > 1: > yield "." + pieces[1] > I dips me lid -- that's far fuglier than mine!!! From claird at lairds.us Fri Jun 2 02:57:06 2006 From: claird at lairds.us (Cameron Laird) Date: Fri, 2 Jun 2006 00:57:06 +0000 Subject: Tkinter - changing existing Dialog? References: Message-ID: <20f4l3-nga.ln1@lairds.us> In article , Michael Yanowitz wrote: >Hello: > > > I have a Tkinter GUI Dialog with many buttons and labels and text >widgets. >What I would like to do is, can I: > >1) Disable/deactivate/hide a button, text widget that is already drawn (and > of course the opposite enable/activate/show it)? . . . import Tkinter root = Tkinter.Tk() def actions(): print "Someone pushed the button." b.configure(state = Tkinter.DISABLED) b = Tkinter.Button(root, text = "Push me", command = actions) b.pack() root.mainloop() From claird at lairds.us Fri Jun 2 03:03:22 2006 From: claird at lairds.us (Cameron Laird) Date: Fri, 2 Jun 2006 01:03:22 +0000 Subject: Tkinter - changing existing Dialog? References: Message-ID: In article , Michael Yanowitz wrote: . . . >2) Change the text of a label or button that is already drawn? > > based on actions taken by the user. Can it be done without destroying >the present dialog or the objects in it and creating a new one? . . . import Tkinter root = Tkinter.Tk() counter = 0 # This is one of several ways one can access the Button's label. def set_text(): b.configure(text = "The button has been pushed %d time(s)." % counter) def actions(): global counter counter += 1 set_text() b = Tkinter.Button(root, command = actions) set_text() b.pack() root.mainloop() From alanalan at newsgroup.nospam Fri Jun 2 03:20:23 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 1 Jun 2006 21:20:23 -0400 Subject: Can Python format long integer 123456789 to 12,3456,789 ? References: <8oKfg.1621$Su3.139425@news20.bellglobal.com> Message-ID: Thanks for help. Is there any comprehensive library for number formatting available on the net? Alan From greg.kujawa at gmail.com Fri Jun 2 03:33:50 2006 From: greg.kujawa at gmail.com (gregarican) Date: 1 Jun 2006 18:33:50 -0700 Subject: New to Python: Do we have the concept of Hash in Python? References: <1149206685.768210.71990@i39g2000cwa.googlegroups.com> Message-ID: <1149212030.851030.257180@c74g2000cwc.googlegroups.com> Dear A.M., The day is complete. My TPS reports still aren't on my desk. Either with or without cover sheets. Not a good time to try to teach yourself a new language. Please gather your belongings and move down to basement storage C. That'd be great, Bill Lumberg John Machin wrote: > A.M wrote: > > > The application is not mission critical system. It is just a simple > > reporting tool. > > Famous last words. From marv at mailcity.com Fri Jun 2 03:35:24 2006 From: marv at mailcity.com (Marvin) Date: 02 Jun 2006 01:35:24 GMT Subject: Inheritance structure less important in dynamic languages? Message-ID: <447f95dc$0$1167$ba620e4c@news.skynet.be> Hi, It's been claimed that inheritance structures are less important in dynamic languages like Python. Why is that and where can i read more about that? /Marv From neuruss at gmail.com Fri Jun 2 04:09:13 2006 From: neuruss at gmail.com (Neuruss) Date: 1 Jun 2006 19:09:13 -0700 Subject: C# equivalent to range() Message-ID: <1149214153.359809.288610@i39g2000cwa.googlegroups.com> I'm sorry for asking about another language here, but since I only know Python and I'm trying to write something in C#, I guess this is the best place... I'd like to know how to write this in C#: x=[] sz = 10000000 x.extend(range(sz)) My question is about "range" and "extend". Is there any equivalent in C#? Thanks in advance, Neuruss From sjmachin at lexicon.net Fri Jun 2 04:14:51 2006 From: sjmachin at lexicon.net (John Machin) Date: 1 Jun 2006 19:14:51 -0700 Subject: C# equivalent to range() In-Reply-To: <1149214153.359809.288610@i39g2000cwa.googlegroups.com> References: <1149214153.359809.288610@i39g2000cwa.googlegroups.com> Message-ID: <1149214491.034665.29030@j55g2000cwa.googlegroups.com> Neuruss wrote: > I'm sorry for asking about another language here, but since I only know > Python and I'm trying to write something in C#, I guess this is the > best place... > Bad guess. Ask questions about language X on comp.lang.X From hancock at anansispaceworks.com Fri Jun 2 04:21:55 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 02 Jun 2006 02:21:55 +0000 Subject: Best Python Editor In-Reply-To: References: Message-ID: <447FA0C3.5030904@anansispaceworks.com> Fredrik Lundh wrote: > "Manoj Kumar P" wrote: > > Can anyone tell me a good python editor/IDE? > emacs! [...] Fredrik Lundh wrote: > "Manoj Kumar P" wrote: > > Can anyone tell me a good python editor/IDE? > vim! There is much truth in this man's replies. ;-D Cheers, Terry -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From aleax at mac.com Fri Jun 2 04:16:14 2006 From: aleax at mac.com (Alex Martelli) Date: Thu, 1 Jun 2006 19:16:14 -0700 Subject: An oddity in list comparison and element assignment References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> Message-ID: <1hg9nl6.xivwcd7n0j5N%aleax@mac.com> wrote: > Hi Alex, > With all due respect to your well-deserved standing in the Python > community, I'm not convinced that equality shouldn't imply invariance > under identical operations. So, why aren't you satisfying my request? Provide a simple concrete definition of what your idea of equality WOULD behave like. I notice that your lack of response stands out like a sore thumb -- all you're providing is a set of constraints you desire and a collection of illfounded analogies and handwaving. Traditional mathematics does not support the concept of "change", nor the distinction between equality and identity; the "real world" has no way to define what modifications are "identical" except by their effects (if the results differ, either the original equality was ill-posited or the modifications were not "identical"). But the real world DOES have the concept of "performing exactly the same sequence of operational steps", and, by THAT definition of "equal modifications", then your assertion: > make identical modifications to the engines of two identical > automobiles, I expect the difference in performance to be identical. is ill-founded -- or, rather, your *expectation* may be ill-founded. Take two systems of any significant complexity that are similar enough to be called "identical" by ALL observers (because trying to ascertain the differences, if any, would inevitably perturb the systems irretrievably by Heisenberg's effect -- i.e., there are no OBSERVABLE differences, which by Occam's Razor requires you to posit the systems are equal, because you cannot prove otherwise -- and entities must not be multiplied beyond necessity, so supposing that "observably equal" systems are indeed equal is Occam-compliant). Now, perform "identical" (ditto) modifications: in the real world, due to quantum effects, there WILL be sub-observable differences in what you're doing to the first one and to the second one. If the systems are unstable to start with, they may well amplify those differences to observable proportions -- and there you are: the effect of the "equal" change on "equal" system may easily become observably unequal. Philosophically, you may classify this as an "observation" of both systems, which reasoning backwards lead you to posit that either the systems were NOT equal to start with or the modifications weren't... that is, IF you also posit determinism, which, as well we know, is an unwarrantedly strong hypothesis for systems in which the differences at quantum level matter. Feel free to follow Einstein (and diverse light-years away from the last few decades of physics) in positing that there MUST exist "hidden variables" (unobservable except maybe in destructive, irreversible ways) explaining the difference -- I'll stick with the mainstream of physics and claim your expectation was badly founded to start with. I can debate epistemology with the best, but this is not really the proper forum for this -- starting with the crucial distinction, what it means, in mathematics OR in the real world, to state that two systems are "equal but NOT identical"? In the end, such debates tend to prove rather futile and unproductive, however. In the world of programming languages, we cut through the chase by requesting *operational* (Brouwer-ian, mathematically speaking) definitions. Provide the *operational* definition of how you WANT equality checking to work, contrast it with my simple two-lines one, and THEN we can have a meaningful debate of which one is the correct one to use in the core of a programming language that has the (blessing and curse of) mutable data objects... Alex From aleax at mac.com Fri Jun 2 04:16:15 2006 From: aleax at mac.com (Alex Martelli) Date: Thu, 1 Jun 2006 19:16:15 -0700 Subject: An oddity in list comparison and element assignment References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> <1149183898.338397.199070@y43g2000cwc.googlegroups.com> Message-ID: <1hg9oed.gknalqf3jq8N%aleax@mac.com> wrote: ... > I agree with Alex that checking for this type of inequality is not a > trivial programming exercise. It requires (at least) a parallel I'm not asking for ANY programming: I'm asking for a *straightforward operational definition*. If the concept which you hanker after is NOT subject to a straightforward operational definition, then I would rule out that said concept could POSSIBLY be "natural". > Alternatively, it might make sense to disallow == for containers by > raising a TypeError although that would eliminate a largely useful > feature. This may be the best example I've ever seen of Emerson's well-known quote about foolish consistency -- except that I don't think this behavior would be "consistent" (either wisely or foolishly) with anything except a vague handwaving set of constraints whose "naturalness" (assuming it's unfeasible to provide a good and straightforward operational definition) is out of the question. Alex From aleax at mac.com Fri Jun 2 04:16:16 2006 From: aleax at mac.com (Alex Martelli) Date: Thu, 1 Jun 2006 19:16:16 -0700 Subject: An oddity in list comparison and element assignment References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> <447f152f@nntp0.pdx.net> <1149194434.528648.148860@u72g2000cwu.googlegroups.com> Message-ID: <1hg9onn.p25evr18a09f9N%aleax@mac.com> Slawomir Nowaczyk wrote: > On Thu, 01 Jun 2006 13:40:34 -0700 > michael.f.ellis at gmail.com wrote: > > #> Scott David Daniels wrote: > #> > Would you say that envelope containing five $100 bills is equal to > #> > an envelope containing five $100 bills with different serial numbers? > > #> Yes (unless I was testing the assertion that the second envelope did > #> not contain counterfeits of the first) > > So, what if Bank of America later decided that bills with serial > numbers containing "7" are no longer valid? Then Wachowia would no doubt be happy to take my business away from BoA;-). I suspect you believe BoA is some kind of "official" body -- it isn't, just like Deutschebank is not one in Germany (rather, Bundesbank is). Just to share some tidbits (about which, as an Italian now living between San Francisco and San Jose, I'm sort of proud of...!-)...: Bank of America is a private bank, founded in San Francisco more than 100 years ago by an Italian-American guy (Amadeo Giannini, born in San Jose, CA, but to Italian-born parents) as "Bank of Italy", then renamed in 1930 in part because the Italian State bank "Banca d'Italia" objected. It rose to prominence right after the SF earthquake of 100 years ago, by opening and staffing a temporary branch to ensure depositors could access their money when they most needed it, while most other banks were staying closed. > In other word, *if* you assume equality must be preserved by future > modifications, than no two different (modifiable) objects can ever be > really equal. Yes, apart from the (slight and understandable!) mistake about BoA's role, this is an excellent example. Here, a global change (to the rule about what banknotes are "equal" to each other, by making some of them invalid and thus unequal to others) perturbs Michaels' desired "strong equality definition" -- to preserve it, equality must degenerate to identity. A Python example would be a change to the default encoding (not officially supported but achievable through a reload(sys), hint;-) which could easily make a bytestring equal, or not, to a Unicode string! Alex From aleax at mac.com Fri Jun 2 04:16:16 2006 From: aleax at mac.com (Alex Martelli) Date: Thu, 1 Jun 2006 19:16:16 -0700 Subject: An oddity in list comparison and element assignment References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> <1149199942.955228.281950@u72g2000cwu.googlegroups.com> Message-ID: <1hg9pbo.1oem3vh1ryksipN%aleax@mac.com> Slawomir Nowaczyk wrote: > On Thu, 01 Jun 2006 15:12:23 -0700 > michael.f.ellis at gmail.com wrote: > > #> I believe that 'is' tests equality of reference, such that > #> > #> >>> a = range(1,3) > #> >>> b = range(1,3) > #> >>> a is b > #> False > #> > #> The 'is' operator tells you whether a and b refer to the same object. > #> What I've been discussing is whether == should test for "structural" > #> equality so that a and b remain equivalent under parallel mutations > #> (and also under single mutations to common references) > > What does "parallel mutations" mean? In particular, what should be the > results of each of the following three comparisons: > > x, y, z = [1],[1],[1] > a, b = [x,y], [y,z] > c, d = [[1],[1]], [[1],[1]] > a == b > c == d > a[0].remove(1) > b[0].remove(1) > a == b > > So, do I understand correctly that you would like first comparison > (a==b) to return "False" and second comparison (c==d) to return > "True"? I sure hope not, since, e.g.: ridiculous = c[0] is not a "mutation" (so equality should still hold, right?), and then it becomes weird to claim that ridiculous.append('bah, humbug!') is a "nonparallel mutation to" c and/or d. In fact, I'm starting to wonder if by Michaels' requirement ANY non-*IDENTICAL* containers (with non-identical mutable items) could EVER be deemed "equal". If he's arguing that "==" should mean exactly the same as "is", that's even crazier than I had gauged so far. But of course, since Michaels still refuses to provide simple, straightforward operational definitions of what it IS that he wants, all of this remains vague and ill-defined. See *WHY* it's so important to provide precision rather than just the handwaving he's given so far? Alex From bignose+hates-spam at benfinney.id.au Fri Jun 2 04:37:13 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 02 Jun 2006 12:37:13 +1000 Subject: C# equivalent to range() References: <1149214153.359809.288610@i39g2000cwa.googlegroups.com> Message-ID: <87zmgwxoyu.fsf@benfinney.id.au> "Neuruss" writes: > I'm sorry for asking about another language here, but since I only > know Python and I'm trying to write something in C#, I guess this is > the best place... Really, it isn't. Post in a C# discussion forum, describing the behaviour you want from your program. -- \ "The only tyrant I accept in this world is the still voice | `\ within." -- Mahatma Gandhi | _o__) | Ben Finney From usenet.rpdillon at xoxy.net Fri Jun 2 04:45:20 2006 From: usenet.rpdillon at xoxy.net (R. P. Dillon) Date: Thu, 01 Jun 2006 19:45:20 -0700 Subject: is a wiki engine based on a cvs/svn a good idea? In-Reply-To: References: Message-ID: <1149215920_13437@sp6iad.superfeed.net> TWiki, written in perl, makes extensive use of versioning/diff functionality you mention through the use of RCS, which, IIRC, is the basis for CVS. This method eliminates the need for the repository as such, and merely requires the presence of the RCS files (and RCS). Unless you _want_ to host your data on a separate machine than the one hosting the wiki, you might consider RCS as an alternative to CVS. OTOH, it is clearly a good idea to base your software on such a tool, given that TWiki does it and has proven to be quite successful. =) Rick piotr malin'ski wrote: > I'm planning to wite a fully featured wiki in Python in one of > frameworks. I've seen some notes about wiki/documentation management > scripts that use SVN as a data storage/versioning. > I've been using SVN a bit but I don't know if it's a good idea to use > it in a wiki engine. Pro: versioning / diffs, Cons: you need your own > svn/cvs repository, can pyLucene or Xapwrap index this? From no at spam.please Fri Jun 2 04:55:57 2006 From: no at spam.please (D H) Date: Thu, 01 Jun 2006 21:55:57 -0500 Subject: C# equivalent to range() In-Reply-To: <1149214153.359809.288610@i39g2000cwa.googlegroups.com> References: <1149214153.359809.288610@i39g2000cwa.googlegroups.com> Message-ID: Neuruss wrote: > I'm sorry for asking about another language here, but since I only know > Python and I'm trying to write something in C#, I guess this is the > best place... > > I'd like to know how to write this in C#: > > x=[] > sz = 10000000 > x.extend(range(sz)) > > My question is about "range" and "extend". Is there any equivalent in > C#? > > Thanks in advance, > Neuruss > List mylist = new List(); for (int i=0; i<10000000; i++) { mylist.Add(i); } You can use AddRange, C# 2.0 anonymous delegates, IEnumerable, yield, foreach, and so forth instead, but for your example this is simplest. Another option is to use boo. http://boo.codehaus.org/ It uses python's syntax but is as fast as C#. The only change you'd have to make in that code is to capitalize the Extend method call. From neuruss at gmail.com Fri Jun 2 05:05:47 2006 From: neuruss at gmail.com (Neuruss) Date: 1 Jun 2006 20:05:47 -0700 Subject: C# equivalent to range() References: <1149214153.359809.288610@i39g2000cwa.googlegroups.com> <1149214491.034665.29030@j55g2000cwa.googlegroups.com> Message-ID: <1149217547.618703.209770@i39g2000cwa.googlegroups.com> John Machin wrote: > Neuruss wrote: > > I'm sorry for asking about another language here, but since I only know > > Python and I'm trying to write something in C#, I guess this is the > > best place... > > > > Bad guess. Ask questions about language X on comp.lang.X Well, perhaps I should. And I should also explain how range and extend work in python, which is almost the same thing... I thougt that maybe some python programmer could have experience here with c# and give me a little hint. But unfortunately, there are people here who are not willing to waste their time helping, but enjoy to waste their time niggling... Thanks anyway! Neuruss From neuruss at gmail.com Fri Jun 2 05:07:07 2006 From: neuruss at gmail.com (Neuruss) Date: 1 Jun 2006 20:07:07 -0700 Subject: C# equivalent to range() In-Reply-To: References: <1149214153.359809.288610@i39g2000cwa.googlegroups.com> Message-ID: <1149217627.026986.215280@i39g2000cwa.googlegroups.com> Thank you DH!! D H wrote: > Neuruss wrote: > > I'm sorry for asking about another language here, but since I only know > > Python and I'm trying to write something in C#, I guess this is the > > best place... > > > > I'd like to know how to write this in C#: > > > > x=[] > > sz = 10000000 > > x.extend(range(sz)) > > > > My question is about "range" and "extend". Is there any equivalent in > > C#? > > > > Thanks in advance, > > Neuruss > > > > List mylist = new List(); > for (int i=0; i<10000000; i++) > { > mylist.Add(i); > } > > You can use AddRange, C# 2.0 anonymous delegates, IEnumerable, yield, > foreach, and so forth instead, but for your example this is simplest. > > Another option is to use boo. http://boo.codehaus.org/ > It uses python's syntax but is as fast as C#. The only change you'd > have to make in that code is to capitalize the Extend method call. From sjmachin at lexicon.net Fri Jun 2 05:08:52 2006 From: sjmachin at lexicon.net (John Machin) Date: 1 Jun 2006 20:08:52 -0700 Subject: C# equivalent to range() In-Reply-To: <1149217547.618703.209770@i39g2000cwa.googlegroups.com> References: <1149214153.359809.288610@i39g2000cwa.googlegroups.com> <1149214491.034665.29030@j55g2000cwa.googlegroups.com> <1149217547.618703.209770@i39g2000cwa.googlegroups.com> Message-ID: <1149217732.260986.295180@u72g2000cwu.googlegroups.com> Neuruss wrote: > John Machin wrote: > > Neuruss wrote: > > > I'm sorry for asking about another language here, but since I only know > > > Python and I'm trying to write something in C#, I guess this is the > > > best place... > > > > > > > Bad guess. Ask questions about language X on comp.lang.X > > Well, perhaps I should. > And I should also explain how range and extend work in python, which is > almost the same thing... > > I thougt that maybe some python programmer could have experience here > with c# and give me a little hint. > > But unfortunately, there are people here who are not willing to waste > their time helping, but enjoy to waste their time niggling... > Plonk. From no at spam.please Fri Jun 2 05:16:38 2006 From: no at spam.please (D H) Date: Thu, 01 Jun 2006 22:16:38 -0500 Subject: Can Python format long integer 123456789 to 12,3456,789 ? In-Reply-To: <8oKfg.1621$Su3.139425@news20.bellglobal.com> References: <8oKfg.1621$Su3.139425@news20.bellglobal.com> Message-ID: A.M wrote: > Hi, > > Is there any built in feature in Python that can format long integer > 123456789 to 12,3456,789 ? Apparently you need to use the locale module. This is the example they give online to print a simple number with commas: import locale locale.setlocale(locale.LC_ALL, 'English_United States.1252') print locale.format("%d", 123456789, grouping=True) Someone should make a module that uses .NET or Java's formmating. You just use {0:n} or ###,### instead of all the above. http://blog.stevex.net/index.php/string-formatting-in-csharp/ http://java.sun.com/docs/books/tutorial/i18n/format/decimalFormat.html From alanalan at newsgroup.nospam Fri Jun 2 05:44:10 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 1 Jun 2006 23:44:10 -0400 Subject: New to Python: Do we have the concept of Hash in Python? References: <1149206685.768210.71990@i39g2000cwa.googlegroups.com> <1149212030.851030.257180@c74g2000cwc.googlegroups.com> Message-ID: <_qOfg.1685$Su3.148290@news20.bellglobal.com> Well the work is done now. I arrived home at 10:30 PM. The application takes data from Oracle 10g stored procedures and renders data to both HTML and CSV formats. The HTML reports have summary and grouping sections and the HTML files are Excel friendly. The application is modular and consists of reusable modules. The application is called every night by scheduled task. The CSV and HTML files are being deployed to Apache for internal employee access. This isn't a complex and big system. Tomorrow, I'll add the email functionality to the application and re-use it's components for more reports. Now that I finished the 1st part of the application, I have to admit that choosing Python was an excellent decision. Python is an awesome programming language with comprehensive library and great community support. I am not that new to Python anymore.. I had a productive day. Thanks everybody for help. "gregarican" wrote in message news:1149212030.851030.257180 at c74g2000cwc.googlegroups.com... > Dear A.M., > > The day is complete. My TPS reports still aren't on my desk. Either > with or without cover sheets. Not a good time to try to teach yourself > a new language. Please gather your belongings and move down to basement > storage C. > > That'd be great, > Bill Lumberg > > John Machin wrote: >> A.M wrote: >> >> > The application is not mission critical system. It is just a simple >> > reporting tool. >> >> Famous last words. > From fredrik at pythonware.com Fri Jun 2 06:51:40 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 02 Jun 2006 06:51:40 +0200 Subject: image lib & Qt4 In-Reply-To: <1149180814.585713.209640@i39g2000cwa.googlegroups.com> References: <1149173540.470829.34940@c74g2000cwc.googlegroups.com> <4e8haiF1dp2heU1@uni-berlin.de> <1149180814.585713.209640@i39g2000cwa.googlegroups.com> Message-ID: aljosa wrote: > does anybody know how to load (in-memory > representation of PNG image) from Qt (v.4.1.3) as QImage? If you want the data from a StringIO object, you can either *read* the data from the object (it's a file-like object, after all), or use the getvalue() method. Something like qim = QImage() qim.loadFromData(f.getvalue()) should work (unless they've changed things around lately). To get better performance, you should be able to use PIL's tostring() method together with the QImage(buffer, width, height, depth, colortable, numColors, bitOrder) form of the QImage constructor. From meng.yan at gmail.com Fri Jun 2 07:01:08 2006 From: meng.yan at gmail.com (Mike Meng) Date: 1 Jun 2006 22:01:08 -0700 Subject: Are there something like "Effective Python"? Message-ID: <1149224468.481470.74580@i39g2000cwa.googlegroups.com> Hi all, I just finished reading Learning Python 3rd ed, and am doing my first Python application, which retrieves and process text and XML documents from Web. Python helped me to write the application in a few hours, I'm very happy with its productivity. But the performance is not satisfactory. I decide to optimized it in Python before trying C/C++ extensions. But I don't know Python much and have no clu to tune my program. Also, I don't know what Pythonist's preferred styles. Are there any books/documents which play the similar role for Python as 'Effective C++' does for C++? For example, one of my friends read my program and suggest me to move the re.compile() out of a for-loop, since the regular pattern is fixed, and re.compile() is slow. I want to find more such advice, where can I find them? Thank you. Mike From max at alcyone.com Fri Jun 2 07:11:38 2006 From: max at alcyone.com (Erik Max Francis) Date: Thu, 01 Jun 2006 22:11:38 -0700 Subject: C# equivalent to range() In-Reply-To: <1149217547.618703.209770@i39g2000cwa.googlegroups.com> References: <1149214153.359809.288610@i39g2000cwa.googlegroups.com> <1149214491.034665.29030@j55g2000cwa.googlegroups.com> <1149217547.618703.209770@i39g2000cwa.googlegroups.com> Message-ID: Neuruss wrote: > I thougt that maybe some python programmer could have experience here > with c# and give me a little hint. > > But unfortunately, there are people here who are not willing to waste > their time helping, but enjoy to waste their time niggling... Yeah, what jerks. They actually wanted to talk about Python, not some random other language that you're trying to learn that has nothing to do with it ... -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis A man can stand a lot as long as he can stand himself. -- Axel Munthe From bignose+hates-spam at benfinney.id.au Fri Jun 2 07:22:58 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 02 Jun 2006 15:22:58 +1000 Subject: Inheritance structure less important in dynamic languages? References: <447f95dc$0$1167$ba620e4c@news.skynet.be> Message-ID: <87verkxhal.fsf@benfinney.id.au> "Marvin" writes: > It's been claimed that inheritance structures are less important in > dynamic languages like Python. Who claimed that? I ask not because I doubt your assertion ("it was claimed"), but rather that if someone claimed something, it seems better to ask that person your next question: > Why is that and where can i read more about that? The person who claimed it is more likely to be able and willing to defend it. -- \ Eccles: "I just saw the Earth through the clouds!" Lew: "Did | `\ it look round?" Eccles: "Yes, but I don't think it saw me." | _o__) -- The Goon Show, _Wings Over Dagenham_ | Ben Finney From luismgz at gmail.com Fri Jun 2 07:36:13 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 1 Jun 2006 22:36:13 -0700 Subject: C# equivalent to range() References: <1149214153.359809.288610@i39g2000cwa.googlegroups.com> <1149214491.034665.29030@j55g2000cwa.googlegroups.com> <1149217547.618703.209770@i39g2000cwa.googlegroups.com> Message-ID: <1149226573.446484.17340@c74g2000cwc.googlegroups.com> Erik Max Francis wrote: > Yeah, what jerks. They actually wanted to talk about Python, not some > random other language that you're trying to learn that has nothing to do > with it ... There are thousands of threads to choose from in this forum. If they didn't like this question, they could have picked any other one to discuss. There's no need to be disagreeable :-) Luis From grflanagan at yahoo.co.uk Fri Jun 2 07:39:33 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 1 Jun 2006 22:39:33 -0700 Subject: grouping a flat list of number by range References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> Message-ID: <1149226773.350717.271520@g10g2000cwb.googlegroups.com> joh12005 at yahoo.fr wrote: > hello, > > i'm looking for a way to have a list of number grouped by consecutive > interval, after a search, for example : > > [3, 6, 7, 8, 12, 13, 15] > > => > > [[3, 4], [6,9], [12, 14], [15, 16]] > > (6, not following 3, so 3 => [3:4] ; 7, 8 following 6 so 6, 7, 8 => > [6:9], and so on) > > i was able to to it without generators/yield but i think it could be > better with them, may be do you an idea? > > best regards, > a list comprehension/itertools version (this won't work with an empty list): from itertools import groupby a = [3, 6, 7, 8, 12, 13, 15] result = [[3, 4], [6,9], [12, 14], [15, 16]] b = [ list(g)[0] for k,g in groupby(range(a[0],a[-1]+2), lambda x: x in a)] c = [ b[i:i+2] for i in range(0,len(a),2) ] assert c == result Gerard From luismgz at gmail.com Fri Jun 2 07:44:44 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 1 Jun 2006 22:44:44 -0700 Subject: Are there something like "Effective Python"? References: <1149224468.481470.74580@i39g2000cwa.googlegroups.com> Message-ID: <1149227084.592329.262420@i39g2000cwa.googlegroups.com> Mike Meng wrote: > Hi all, > I just finished reading Learning Python 3rd ed, and am doing my > first Python application, which retrieves and process text and XML > documents from Web. Python helped me to write the application in a few > hours, I'm very happy with its productivity. But the performance is not > satisfactory. I decide to optimized it in Python before trying C/C++ > extensions. But I don't know Python much and have no clu to tune my > program. Also, I don't know what Pythonist's preferred styles. Are > there any books/documents which play the similar role for Python as > 'Effective C++' does for C++? > > For example, one of my friends read my program and suggest me to > move the re.compile() out of a for-loop, since the regular pattern is > fixed, and re.compile() is slow. I want to find more such advice, where > can I find them? > > Thank you. > > Mike http://wiki.python.org/moin/PythonSpeed/PerformanceTips Also, I suggest checking Psyco ( http://psyco.sourceforge.net/ ), which can easily improve your program's speed with no change in your code. Hope this helps... Luis From grflanagan at yahoo.co.uk Fri Jun 2 07:48:15 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 1 Jun 2006 22:48:15 -0700 Subject: grouping a flat list of number by range In-Reply-To: <1149226773.350717.271520@g10g2000cwb.googlegroups.com> References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> <1149226773.350717.271520@g10g2000cwb.googlegroups.com> Message-ID: <1149227295.288802.278990@i39g2000cwa.googlegroups.com> Gerard Flanagan wrote: > joh12005 at yahoo.fr wrote: > > hello, > > > > i'm looking for a way to have a list of number grouped by consecutive > > interval, after a search, for example : > > > > [3, 6, 7, 8, 12, 13, 15] > > > > => > > > > [[3, 4], [6,9], [12, 14], [15, 16]] > > > > (6, not following 3, so 3 => [3:4] ; 7, 8 following 6 so 6, 7, 8 => > > [6:9], and so on) > > > > i was able to to it without generators/yield but i think it could be > > better with them, may be do you an idea? > > > > best regards, > > > > a list comprehension/itertools version (this won't work with an empty > list): > > from itertools import groupby > > a = [3, 6, 7, 8, 12, 13, 15] > > result = [[3, 4], [6,9], [12, 14], [15, 16]] > > b = [ list(g)[0] for k,g in groupby(range(a[0],a[-1]+2), lambda x: > x in a)] > > c = [ b[i:i+2] for i in range(0,len(a),2) ] > > assert c == result > > > Gerard change len(a) to len(b) in case a has duplicates like [3,3,3,6,7,8,12,13,15] Gerard From fredrik at pythonware.com Fri Jun 2 08:01:26 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 02 Jun 2006 08:01:26 +0200 Subject: image lib & Qt4 In-Reply-To: References: <1149173540.470829.34940@c74g2000cwc.googlegroups.com> <4e8haiF1dp2heU1@uni-berlin.de> <1149180814.585713.209640@i39g2000cwa.googlegroups.com> Message-ID: Fredrik Lundh wrote: > To get better performance, you should be able to use PIL's tostring() > method together with the QImage(buffer, width, height, depth, > colortable, numColors, bitOrder) form of the QImage constructor. for PyQt4, that seems to have changed to QImage(buffer, width, height, format), where format is a QImage.Format_XXX specifier. in other words, this should work: if im.mode != "RGB": im = im.convert("RGB") data = im.tostring("raw", "BGRX") image = QImage(data, im.size[0], im.size[1], QImage.Format_RGB32) note that the QImage descriptor will point into the data buffer, so you must hang on to data for as long you're using image. (I haven't found a way to attach a user attribute to a QImage class; it doesn't complain when I do that, but it doesn't seem to do the right thing...) From ray_usenet at yahoo.com Fri Jun 2 08:02:17 2006 From: ray_usenet at yahoo.com (Ray) Date: 1 Jun 2006 23:02:17 -0700 Subject: Are there something like "Effective Python"? In-Reply-To: <1149224468.481470.74580@i39g2000cwa.googlegroups.com> References: <1149224468.481470.74580@i39g2000cwa.googlegroups.com> Message-ID: <1149228137.540238.161060@f6g2000cwb.googlegroups.com> I think Aahz stated somewhere that he was workign on Effective Python. I'm not sure if it's an ongoing plan or it's been canned though? Mike Meng wrote: > Hi all, > I just finished reading Learning Python 3rd ed, and am doing my > first Python application, which retrieves and process text and XML > documents from Web. Python helped me to write the application in a few > hours, I'm very happy with its productivity. But the performance is not > satisfactory. I decide to optimized it in Python before trying C/C++ > extensions. But I don't know Python much and have no clu to tune my > program. Also, I don't know what Pythonist's preferred styles. Are > there any books/documents which play the similar role for Python as > 'Effective C++' does for C++? > > For example, one of my friends read my program and suggest me to > move the re.compile() out of a for-loop, since the regular pattern is > fixed, and re.compile() is slow. I want to find more such advice, where > can I find them? > > Thank you. > > Mike From mcPas.De.Spam at mclaveauPas.De.Spam.com Fri Jun 2 08:12:34 2006 From: mcPas.De.Spam at mclaveauPas.De.Spam.com (Michel Claveau) Date: Fri, 02 Jun 2006 08:12:34 +0200 Subject: C# equivalent to range() References: <1149214153.359809.288610@i39g2000cwa.googlegroups.com> <1149214491.034665.29030@j55g2000cwa.googlegroups.com> <1149217547.618703.209770@i39g2000cwa.googlegroups.com> <1149226573.446484.17340@c74g2000cwc.googlegroups.com> Message-ID: Hi! > There are thousands of threads to choose from in this forum. > If they didn't like this question, they could have picked any other one > to discuss. > There's no need to be disagreeable :-) I think the same thing. -- @-salutations Michel Claveau From rpdooling at gmail.com Fri Jun 2 08:17:35 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 1 Jun 2006 23:17:35 -0700 Subject: Are there something like "Effective Python"? References: <1149224468.481470.74580@i39g2000cwa.googlegroups.com> Message-ID: <1149229055.088793.89010@i39g2000cwa.googlegroups.com> >> I just finished reading Learning Python 3rd ed, For real? I thought there was only a 2nd edition. http://www.oreilly.com/catalog/lpython2/ From paddy3118 at netscape.net Fri Jun 2 08:18:26 2006 From: paddy3118 at netscape.net (Paddy) Date: 1 Jun 2006 23:18:26 -0700 Subject: grouping a flat list of number by range In-Reply-To: <127ut85lpcmoa5b@corp.supernews.com> References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> <1149201416.196975.123370@c74g2000cwc.googlegroups.com> <127urvnrbvjgr07@corp.supernews.com> <1149202780.780252.242110@f6g2000cwb.googlegroups.com> <127ut85lpcmoa5b@corp.supernews.com> Message-ID: <1149229106.062837.139960@j55g2000cwa.googlegroups.com> Jim Segrave wrote: > In article <1149202780.780252.242110 at f6g2000cwb.googlegroups.com>, > Paddy wrote: > > > >What I ran was more like the version below, but i did a quick > >separation of the line that has the ';' in it and goofed. > > > >>>> def interv2(inlist): > >... for i,val in enumerate(inlist): > >... if i==0: > >... tmp = val > >... elif val != valinc: > >... yield [tmp, valinc]; tmp = val > >... valinc = val+1 > >... yield [tmp, valinc] > >... > >>>> list(interv2(inlist)) > >[[3, 4], [6, 9], [12, 14], [15, 16]] > > Fails on an empty list, as tmp is not defined when it hits the yield > > > -- > Jim Segrave (jes at jes-2.demon.nl) Yep, I still, purposfully, decided not to put any guard checks in because: Its very easy to add. It detracts from the algorithm. It might never be called with an empty list in-situ. It is correct for the original posters testcases. Yah gotta leave-em something to do ;-) But you-too are right. Don't just cut-n-paste newsgroup solutions. they need testing for your particular use. I doubt anyone on C.L.P. would be malicious, but your actual use of a function having a wider scope to inputs than mentioned might be fairy common. (Damn, I wanted to use 'caveat emptor', but it does not apply as nothing is being bought. Oh well :-) -- Pad. From praveenkumar.117 at gmail.com Fri Jun 2 08:42:16 2006 From: praveenkumar.117 at gmail.com (praveenkumar.117 at gmail.com) Date: 1 Jun 2006 23:42:16 -0700 Subject: Import Issue Message-ID: <1149230536.375190.12150@c74g2000cwc.googlegroups.com> Hi all, I am facing a problem while importing a file in python script. After doing import file i am updating that file. Later i am accessing a dictionary contained in that file. Eventhough changes are reflected in the file... When i access a dictionary those changes are not there. I believe that it is accessing from the object file that is created when i did import at the start of the script. I will be kind enough if somebody suggest solution to this problem. Regards- praveen From paddy3118 at netscape.net Fri Jun 2 09:12:38 2006 From: paddy3118 at netscape.net (Paddy) Date: 2 Jun 2006 00:12:38 -0700 Subject: grouping a flat list of number by range In-Reply-To: <447F79C9.6080407@lexicon.net> References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> <1149201416.196975.123370@c74g2000cwc.googlegroups.com> <447F79C9.6080407@lexicon.net> Message-ID: <1149232358.817706.92680@j55g2000cwa.googlegroups.com> John Machin wrote: > On 2/06/2006 8:36 AM, Paddy wrote: > > Oh the siren call of every new feature in the language! > enumerate() just to get a first-time test, and then botch it?? > > Read the following; the replacement version uses a simple old-fashioned > inelegant flag, works with an empty sequence, and doesn't depend on the > input being sliceable or indexable. > > HTH, > John > Thanks, un-botchable John. What if the poster doesn't send a null list? What if the correct result for a null list is "spam"; or an exception? What if.... ... we toned down the language? Cheers, Pad. :-) From sreeram at tachyontech.net Fri Jun 2 08:28:07 2006 From: sreeram at tachyontech.net (Sreeram Kandallu) Date: Fri, 02 Jun 2006 11:58:07 +0530 Subject: tp_richcompare Message-ID: <447FDA77.4060507@tachyontech.net> I'm writing an extension type, for which i'd like to implement only == and !=, but not the other comparison operators like <,<=,>,>=. What is the right way to do this? I currently have a tp_richcompare function, which handles Py_EQ, and Py_NE, but raises a TypeError for the other operations. Is this the 'right' way? Sreeram -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 252 bytes Desc: OpenPGP digital signature Url : http://mail.python.org/pipermail/python-list/attachments/20060602/c19c9de7/attachment.pgp From fredrik at pythonware.com Fri Jun 2 09:30:56 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 2 Jun 2006 09:30:56 +0200 Subject: New to Python: Do we have the concept of Hash in Python? References: <%aIfg.3027$EF1.232063@news20.bellglobal.com> Message-ID: "A.M" wrote: >> are your boss aware of this ? > > In fact my boss is quite impressed with my progress so far. *your* progress ? From tim.golden at viacom-outdoor.co.uk Fri Jun 2 09:41:52 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 2 Jun 2006 08:41:52 +0100 Subject: win32com: how to connect to a specific instance of a running object? Message-ID: [ago] | Is it possible to use win32com.client to connect to a | specific instance | of a running application? In particular I am interested in finding the | instance of excel which has a particular spreadsheet opened | considering | that there might be more instances of excel running at the | same time. I | need to take a "snapshot" of the spreadsheet which contains | live feeds. Not something I've tried myself, but perhaps this post/thread might help: http://groups.google.com/group/comp.lang.python/msg/d985ada28948dcd8 (I cheated slightly when I Googled because I knew that GetActiveObject was something to do with the business) TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From Serge.Orlov at gmail.com Fri Jun 2 09:44:30 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 2 Jun 2006 00:44:30 -0700 Subject: struct: type registration? References: <447e4b98$1@news.eftel.com> <1149185926.636174.48970@y43g2000cwc.googlegroups.com> <447F6F64.400@lexicon.net> Message-ID: <1149234270.300072.316880@c74g2000cwc.googlegroups.com> John Machin wrote: > On 2/06/2006 4:18 AM, Serge Orlov wrote: > > If you want to parse binary data use pyconstruct > > > > > > Looks promising on the legibility and functionality fronts. Can you make > any comment on the speed? I don't know really. I used it for small data parsing, its performance was acceptable. As I understand it is implemented right now as pure python code using struct under the hood. The biggest concern is the lack of comprehensive documentation, if that scares you, it's not for you. > Reason for asking is that Microsoft Excel > files have this weird "RK" format for expressing common float values in > 32 bits (refer http://sc.openoffice.org, see under "Documentation" > heading). I wrote and support the xlrd module (see > http://cheeseshop.python.org/pypi/xlrd) for reading those files in > portable pure Python. Below is a function that would plug straight in as > an example of Giovanni's custom unpacker functions. Some of the files > can be very large, and reading rather slow. I *guess* that the *current* implementation of pyconstruct will make parsing slightly slower. But you have to try to find out. > from struct import unpack > > def unpack_RK(rk_str): # arg is 4 bytes > flags = ord(rk_str[0]) > if flags & 2: > # There's a SIGNED 30-bit integer in there! > i, = unpack(' i >>= 2 # div by 4 to drop the 2 flag bits > if flags & 1: > return i / 100.0 > return float(i) > else: > # It's the most significant 30 bits > # of an IEEE 754 64-bit FP number > d, = unpack(' if flags & 1: > return d / 100.0 > return d I had to lookup what < means :) Since nobody except this function cares about internals of RK number, you don't need to use pyconstruct to parse at bit level. The code will be almost like you wrote except you replace unpack(' after del list , when I use it again, prompt 'not defined'.how could i delete its element,but not itself? except list.remove(val) ,are there other ways to delete list 's elements? and , I wrote: list1=[] def method1(): global list1 list1=['a','b','c','d'] def method2(): list2=list1 list2.remove['a'] main(): global list1 method1() method2() print list1[0] it prints 'b'. How could I keep the list1 not to change when remove list2's elements? From iainking at gmail.com Fri Jun 2 10:10:36 2006 From: iainking at gmail.com (Iain King) Date: 2 Jun 2006 01:10:36 -0700 Subject: Trying to get FreeImagePy to work. In-Reply-To: <1149192520.959302.250840@j55g2000cwa.googlegroups.com> References: <1148651668.578852.3160@i40g2000cwc.googlegroups.com> <7fEdg.13375$cX1.201311@twister2.libero.it> <1148655611.990937.322350@j73g2000cwa.googlegroups.com> <1149166096.176405.22780@i40g2000cwc.googlegroups.com> <3PCfg.20835$cX1.315781@twister2.libero.it> <1149174938.337973.85950@g10g2000cwb.googlegroups.com> <1149192520.959302.250840@j55g2000cwa.googlegroups.com> Message-ID: <1149235836.646855.164110@i40g2000cwc.googlegroups.com> Iain King wrote: > Michele Petrazzo wrote: > > Iain King wrote: > > > However, when I'm do the > > > fipy.convertToPil(), it inverts the image? > > > > No, it not invert the image... It only return the image as is. > > > > > I've inserted a > > > fipy.invert() before the conversion as a temporary fix, but is there a > > > reason for this? > > > > If you are have a min-is-white image (fax ?) that isn't the standard, > > you will have an "inverted" image, because PIl expect a min-is-black > > image! > > > > > This is probably what is happening. I'll upload one of the images > tomorrow, and you can check it out to make sure. > > > > > relevant code: > > > > > > def getHeaders(files): > > > thumbs = [] > > > for f in files: > > > print "Adding %s" % f > > > fi = FIPY.Image(f) > > > fi.setCurrentPage(0) > > > fi.invert() #temp fix > > > thumb = fi.convertToPil() > > > thumb.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS) > > > thumbs.append((os.path.basename(f), pilToBitmap(thumb))) > > > thumbs.sort() > > > return thumbs > > > > Just a question, why "thumbs.sort" ? Inside this list you have only > > images! > > Ah, look closer! It's a list of tuples: (filename, image) > I'll try out FIPY's resizing tomorrow too. OTOH, I have functions to > convert between PIL and wxPython, and functions to convert betweem PIL > and FIPY, but I don't see a function to convert FIPY to wxPython? > Image at: http://www.snakebomb.com/misc/example.tif Iain From meng.yan at gmail.com Fri Jun 2 10:15:38 2006 From: meng.yan at gmail.com (Mike Meng) Date: 2 Jun 2006 01:15:38 -0700 Subject: Are there something like "Effective Python"? In-Reply-To: <1149229055.088793.89010@i39g2000cwa.googlegroups.com> References: <1149224468.481470.74580@i39g2000cwa.googlegroups.com> <1149229055.088793.89010@i39g2000cwa.googlegroups.com> Message-ID: <1149236138.364915.189890@i40g2000cwc.googlegroups.com> Bart, I'm sorry, it's 2nd edtion. Thanks. mike BartlebyScrivener ??? > >> I just finished reading Learning Python 3rd ed, > > For real? I thought there was only a 2nd edition. > > http://www.oreilly.com/catalog/lpython2/ From bearophileHUGS at lycos.com Fri Jun 2 10:19:15 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 2 Jun 2006 01:19:15 -0700 Subject: after del list , when I use it again, prompt 'not defined'.how could i delete its element, but not itself? In-Reply-To: <1149235087.256704.309360@g10g2000cwb.googlegroups.com> References: <1149235087.256704.309360@g10g2000cwb.googlegroups.com> Message-ID: <1149236355.221540.136120@y43g2000cwc.googlegroups.com> python wrote: > after del list , when I use it again, prompt 'not defined'.how could i > delete its element,but not itself? This is a way: >>> a = range(10) >>> del a[:] >>> a [] >>> a.append(20) >>> a [20] Bye, bearophile From laurent.pointal at limsi.fr Fri Jun 2 10:21:12 2006 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Fri, 02 Jun 2006 10:21:12 +0200 Subject: How to format datetime values In-Reply-To: References: <1149190242.446952.52180@j55g2000cwa.googlegroups.com> Message-ID: A.M a ?crit : > "BartlebyScrivener" wrote in message > news:1149190242.446952.52180 at j55g2000cwa.googlegroups.com... >> Are you trying to get banned, or what? >> >> It's the equivalent of me asking you: >> >> Hey, does Ruby have anything like dictionaries and will you teach me >> about strings? Oh, and what's an object? >> >> Go read the bleeping tutorial. >> >> rd >> > > Well, I did investigate all tutorial and google and I wasn't able to find > any built-in way for datetime formatting in Python. Really ? For time formating... have you really really looked at module... 'time'? > In fact I cannot find > any way to format a long integer into 99,999,9999 format. I know how > to format strings with C printf like formatter, but I am sure what I > am trying to do can't be done with C printf formatting. For long integer formating like your example, its not direct - maybe look at locale formating of numbers (module... 'locale'). And I recently annouce the PQRC (on clp.announce), which can gives you some directions: http://www.limsi.fr/Individu/pointal/python/pqrc/ A+ Laurent. From maric at aristote.info Fri Jun 2 10:27:11 2006 From: maric at aristote.info (Maric Michaud) Date: Fri, 2 Jun 2006 10:27:11 +0200 Subject: An oddity in list comparison and element assignment In-Reply-To: <1149199942.955228.281950@u72g2000cwu.googlegroups.com> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1149199942.955228.281950@u72g2000cwu.googlegroups.com> Message-ID: <200606021027.12616.maric@aristote.info> Le Vendredi 02 Juin 2006 00:12, michael.f.ellis at gmail.com a ?crit?: > I believe that 'is' tests equality of reference, such that > > >>> a = range(1,3) > >>> b = range(1,3) > >>> a is b > > False > > The 'is' operator tells you whether a and b refer to the same object. Yeah ! That's it. And you proposed a definition of identity : for all operator op, op(a) = op(b) => a = b This is of poor use in real life where two thing are never identical, just comparable. > What I've been discussing is whether == should test for "structural" > equality so that a and b remain equivalent under parallel mutations > (and also under single mutations to common references) So you wanted a comparison opertor of twto sequence dafined like this : seq1 == seq2 => for all e in seq1, seq2[seq1.index(e) *is* e !!! this would not be very useful nor consistent I guess and prefer the one used in python : seq1 == seq2 => for all e in seq1, seq2[seq1.index(e) == e -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From laurent.pointal at limsi.fr Fri Jun 2 10:26:28 2006 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Fri, 02 Jun 2006 10:26:28 +0200 Subject: Python for Visual Basic or C# programmers In-Reply-To: References: Message-ID: A.M a ?crit : > Hi, > > > > I am trying to find the equivalent functions such as vb's str or asc in > Python. Is there any resource that help me to find these kinds of functions > in Python faster? I've written the PQRC for that purpose: http://www.limsi.fr/Individu/pointal/python/pqrc/ A+ Laurent. From ziga.seilnacht at gmail.com Fri Jun 2 10:28:14 2006 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 2 Jun 2006 01:28:14 -0700 Subject: tp_richcompare References: Message-ID: <1149236894.705238.224090@c74g2000cwc.googlegroups.com> Sreeram Kandallu wrote: > I'm writing an extension type, for which i'd like to implement only == > and !=, but not the other comparison operators like <,<=,>,>=. > What is the right way to do this? > I currently have a tp_richcompare function, which handles Py_EQ, and > Py_NE, but raises a TypeError for the other operations. Is this the > 'right' way? Yes. This is exactly what the builtin complex type does. > Sreeram > Ziga From norbert at akumakun.de Fri Jun 2 10:53:51 2006 From: norbert at akumakun.de (Norbert Kaufmann) Date: Fri, 02 Jun 2006 10:53:51 +0200 Subject: How do you practice Python? In-Reply-To: <1149152214.215907.31800@i39g2000cwa.googlegroups.com> References: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> <447eaae0$0$20867$636a55ce@news.free.fr> <1149152214.215907.31800@i39g2000cwa.googlegroups.com> Message-ID: Ray wrote: [...] > Um, I mean, what if you have to use something other than > Python/Jython/IronPython? :) How do you keep your Python skill sharp? > You could use IPython as your primary shell. Than you have the opportunity to do all these nasty automation tasks -- create test data, deploy configuration files, search in logfiles for errors, etc. -- for your project in Python. Convince your project manager to develop prototypes. No one in your company is better and faster in prototyping than the Python expert Ray. HTH Norbert -- It is easier to get forgiveness than permission. From chris.cavalaria at free.fr Fri Jun 2 11:03:34 2006 From: chris.cavalaria at free.fr (Christophe) Date: Fri, 02 Jun 2006 11:03:34 +0200 Subject: Function mistaken for a method In-Reply-To: References: <447eed61$0$20860$626a54ce@news.free.fr> Message-ID: <447ffed3$0$6176$626a54ce@news.free.fr> Maric Michaud a ?crit : > Le Jeudi 01 Juin 2006 15:36, Christophe a ?crit : > >> self.x = self.__class__.f(0) > > nope, this will result in a TypeError "unbound method must be called with > instance as first argument" Your right :( staticmethod it is then. From feel.energetic at gmail.com Fri Jun 2 11:07:01 2006 From: feel.energetic at gmail.com (feel_energetic) Date: 2 Jun 2006 02:07:01 -0700 Subject: how to define a static field of a given class Message-ID: <1149239221.045268.6170@g10g2000cwb.googlegroups.com> Hi, I already knew how to define a static method of a class( using staticmethod() ),but I find there isn't a built-in func to build a static field ( something like staticfield() ) can anyone help me on this? thanks very much for your help :) From maric at aristote.info Fri Jun 2 11:26:13 2006 From: maric at aristote.info (Maric Michaud) Date: Fri, 2 Jun 2006 11:26:13 +0200 Subject: how to define a static field of a given class In-Reply-To: <1149239221.045268.6170@g10g2000cwb.googlegroups.com> References: <1149239221.045268.6170@g10g2000cwb.googlegroups.com> Message-ID: <200606021126.14068.maric@aristote.info> Le Vendredi 02 Juin 2006 11:07, feel_energetic a ?crit?: > Hi, > > I already knew how to define a static method of a class( using > staticmethod() ),but I find there isn't a built-in func to build a > static field ( something like staticfield() ) > can anyone help me on this? > thanks very much for your help :) I guess you come from a c++ background, and what you mean by static field is a variable shared by all instance of the class, right ? then, class toto : VAL=5 but, you can't assign directly via instances of the class as it will override VAL in the instance : In [2]: t=toto() In [3]: t.VAL=4 In [4]: toto.VAL Out[4]: 5 In [5]: t.__dict__ Out[5]: {'VAL': 4} You must explicitly modify t.__class__.VAL or toto.VAL : In [8]: t1, t2 = toto(), toto() In [9]: t1.__class__.VAL = 4 In [10]: t2.VAL Out[10]: 4 -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From onurb at xiludom.gro Fri Jun 2 11:24:07 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 02 Jun 2006 11:24:07 +0200 Subject: Conditional Expressions in Python 2.4 In-Reply-To: References: Message-ID: <4480042b$0$29879$636a55ce@news.free.fr> A.M wrote: > Hi, > > > > I am using Python 2.4. I read the PEP 308 at: > > http://www.python.org/dev/peps/pep-0308/ > > I tried the statement: > > a= "Yes" if 1==1 else "No" > > but the interpreter doesn't accept it. > > Do we have the conditional expressions in Python 2.4? No, AFAIK they'll be in for 2.5 In the meanwhile, there are (sometime tricky? ways to get the same result: a = 1 == 1 and "Yes" or "No" a = ("No", "Yes")[1 == 1] -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From ullrich at math.okstate.edu Fri Jun 2 11:30:20 2006 From: ullrich at math.okstate.edu (David C. Ullrich) Date: Fri, 02 Jun 2006 04:30:20 -0500 Subject: shuffling elements of a list References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> <1149051212.139046.155340@c74g2000cwc.googlegroups.com> <1149105576.321676.131600@j55g2000cwa.googlegroups.com> <69ft72516amvri3up8fop5rf543s6en1lg@4ax.com> Message-ID: On Thu, 01 Jun 2006 03:25:23 -0700, Erik Max Francis wrote: >David C. Ullrich wrote: > >> Good example, because we know that EMF is not dumb. I've seen >> the same algorithm many times - the best example is ... > >Man, an error made _six years ago_ and people are still bringing it up ... Sorry. Happens to me on sci.math all the time. The point really wasn't that you were so dumb, the point was just the opposite. (_I_ didb't bring it up, btw - I would never have known about it if FL hadn't pointed it out.) ************************ David C. Ullrich From rtw at freenet.co.uk Fri Jun 2 11:28:25 2006 From: rtw at freenet.co.uk (Rob Williscroft) Date: Fri, 02 Jun 2006 04:28:25 -0500 Subject: how to define a static field of a given class References: <1149239221.045268.6170@g10g2000cwb.googlegroups.com> Message-ID: feel_energetic wrote in news:1149239221.045268.6170 @g10g2000cwb.googlegroups.com in comp.lang.python: > Hi, > > I already knew how to define a static method of a class( using > staticmethod() ),but I find there isn't a built-in func to build a > static field ( something like staticfield() ) > can anyone help me on this? > thanks very much for your help :) > What you possibly want is just a class attribute: class MyClass( object ): static_field = 10 myInstance = MyClass() print MyClass.static_field, myInstance.static_field Rob. -- http://www.victim-prime.dsl.pipex.com/ From doug.bromley at gmail.com Fri Jun 2 11:38:41 2006 From: doug.bromley at gmail.com (Doug Bromley) Date: Fri, 2 Jun 2006 10:38:41 +0100 Subject: How do you practice Python? In-Reply-To: References: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> <447eaae0$0$20867$636a55ce@news.free.fr> <1149152214.215907.31800@i39g2000cwa.googlegroups.com> Message-ID: <288425520606020238k7f901df5ke5b1a2aba020e654@mail.gmail.com> On 6/2/06, Norbert Kaufmann wrote: > > Ray wrote: > [...] > > Um, I mean, what if you have to use something other than > > Python/Jython/IronPython? :) How do you keep your Python skill sharp? > > > > You could use IPython as your primary shell. Than you have the > opportunity to do all these nasty automation tasks -- create test data, > deploy configuration files, search in logfiles for errors, etc. -- for > your project in Python. > > Convince your project manager to develop prototypes. No one in your > company is better and faster in prototyping than the Python expert Ray. > > HTH > > Norbert > > -- > It is easier to get forgiveness than permission. > -- > http://mail.python.org/mailman/listinfo/python-list I've got a couple of posts at my blog that could help you here because I've often had your problem with new languages. http://straw-dogs.co.uk/blog/01/26/practice-makes-perfect/ <-- A list of resources such as quizes, practice, games, tests and info. http://straw-dogs.co.uk/blog/05/31/scripting-an-easy-life/ <-- Just some ideas for automating tasks on your system(s). All the best. Doug -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/python-list/attachments/20060602/fc1e4af4/attachment.html From onurb at xiludom.gro Fri Jun 2 11:40:21 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 02 Jun 2006 11:40:21 +0200 Subject: Inheritance structure less important in dynamic languages? In-Reply-To: <447f95dc$0$1167$ba620e4c@news.skynet.be> References: <447f95dc$0$1167$ba620e4c@news.skynet.be> Message-ID: <448007f9$0$20891$626a54ce@news.free.fr> Marvin wrote: > Hi, > > It's been claimed s/claimed/observed/ In Python and Ruby, class hierarchies tends to be *really* flat when compared to Java or C++. > that inheritance structures are less important in dynamic > languages like Python. Why is that Don't you guess ?-) A very obvious point is that in a dynamically typed language, inheritence is only about implementation - it's not used for class-based polymorphism (subtyping). Also, dynamic languages are usually very strong on introspection and offer good support for automatic delegation ("DoesNotUnderstand" in Smalltalk, __getattr__ in Python, etc), which tend to lower the use of inheritence for "private inheritence" (ie: implementation reuse without any subtyping semantic). This leaves with only three real use-case for inheritence : * factoring common features of a set of related classes in an abstract base class * specialisation of an existing class (proper subclassing), * mixins. > and where can i read more about that? "duck typing", "implied interface" and "composition/delegation" could be good starting points for a google search. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From onurb at xiludom.gro Fri Jun 2 11:47:47 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 02 Jun 2006 11:47:47 +0200 Subject: how to define a static field of a given class In-Reply-To: <1149239221.045268.6170@g10g2000cwb.googlegroups.com> References: <1149239221.045268.6170@g10g2000cwb.googlegroups.com> Message-ID: <448009b7$0$12763$636a55ce@news.free.fr> feel_energetic wrote: > Hi, > > I already knew how to define a static method of a class( using > staticmethod() ), FWIW, it's probably one of the most useless construct in Python IMHO. classmethod are really much more useful to me. > but I find there isn't a built-in func to build a > static field ( something like staticfield() ) Please define "static field", I just don't understand what it could be. Now if what you want is a class attribute (ie: an attribute that is shared by all instances of a class), just declare it at the class level: class MyClass(object): shared_attrib = 42 # can be accessed via the class # or via an instance MyClass.shared_attrib m = MyClass() m.shared_attrib # but you don't want to rebind it via an instance m.shared_attrib = 33 m.shared_attrib MyClass.shared_attrib # note that the problem is only with rebinding - mutating is ok class MyOtherClass(object): shared_attrib = [42] mo = MyOtherClass() mo.shared_attrib mo.shared_attrib.append(33) mo.shared_attrib MyOtherClass.shared_attrib HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From maric at aristote.info Fri Jun 2 12:19:09 2006 From: maric at aristote.info (Maric Michaud) Date: Fri, 2 Jun 2006 12:19:09 +0200 Subject: how to define a static field of a given class In-Reply-To: <448009b7$0$12763$636a55ce@news.free.fr> References: <1149239221.045268.6170@g10g2000cwb.googlegroups.com> <448009b7$0$12763$636a55ce@news.free.fr> Message-ID: <200606021219.09548.maric@aristote.info> Le Vendredi 02 Juin 2006 11:47, bruno at modulix a ?crit?: > FWIW, it's probably one of the most useless construct in Python IMHO. > classmethod are really much more useful to me. +1 I do prefer classmethod, both for the name and behavior (everything should be intended for polymorphism, after all, classes are just instances of type). -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From feel.energetic at gmail.com Fri Jun 2 12:21:07 2006 From: feel.energetic at gmail.com (feel_energetic) Date: 2 Jun 2006 03:21:07 -0700 Subject: how to define a static field of a given class In-Reply-To: <448009b7$0$12763$636a55ce@news.free.fr> References: <1149239221.045268.6170@g10g2000cwb.googlegroups.com> <448009b7$0$12763$636a55ce@news.free.fr> Message-ID: <1149243667.724683.80090@g10g2000cwb.googlegroups.com> thanks for all of your replies I did this before I posted the subject but got (NameError: global name 'startTime' is not defined) the most important thing i didn't know is "the static field should be referred with the qualifier ClassName" it's a little different from C++ :) (the static field can directly referred without the ClassName) From yairchu at gmail.com Fri Jun 2 12:35:49 2006 From: yairchu at gmail.com (yairchu at gmail.com) Date: 2 Jun 2006 03:35:49 -0700 Subject: struct: type registration? In-Reply-To: References: Message-ID: <1149244549.497806.211280@y43g2000cwc.googlegroups.com> using struct for the stuff you're up to and you'll finish with weird unmaintainable code. save yourself a lot of pain and use construct instead. http://pyconstruct.wikispaces.com/ From jonathan.wright at gmail.com Fri Jun 2 12:38:28 2006 From: jonathan.wright at gmail.com (Jon) Date: 2 Jun 2006 03:38:28 -0700 Subject: import confused by contents of working directory Message-ID: <1149244708.049852.153980@i39g2000cwa.googlegroups.com> It appears that (windows) python searches in the current working directory before looking in the local site-packages directory, or that '.' comes first in sys.path? The problem arises when I made the mistake of running a test program from the same directory where I built and installed my package. Python uses the package from the current directory, which misses the pyd files, instead of the site-packages package which has them installed. Would somebody please explain how to know what is going on when an import statement is ambiguous? If the interpreter has several choices about what to import then which one is chosen? I apologise if this is FAQ, but it seems that if I say "import mymodule" and the interpreter finds more than one option for mymodule it could raise an Exception asking "which one do you want??" instead of silently picking up the first thing it finds? This would be perhaps a major change - but I expect "import" to go look in the python installation and would look for a command like "load" to go looking for specific filenames or find things that are hanging around in the current working directory. Is there any plan for a statement like: "from future import PleaseDontJustGuessWhatToImport" ? Thanks in advance for any useful advice, perhaps I am just missing the out on the "right way to do it"? It is normal to remove '.' from sys.path at the start of a script? Jon ------------------------------------- Some examples of my confusion are outlined below. I use Numeric only because I assume they are doing a proper installation. I had thought for a long time that I had this problem because I was screwing up with distutils or .pth files etc etc. c:\> mkdir import c:\> cd import c:\import> python -c "import Numeric; print 'OK!'" OK! c:\import> echo raise Exception("Not OK! Local py file") > Numeric.py c:\import> python -c "import Numeric;print 'OK!'" Traceback (most recent call last): File "", line 1, in ? File "Numeric.py", line 1, in ? raise Exception("Not OK! Local py file") Exception: Not OK! Local py file c:\import> del Numeric.py c:\import> mkdir Numeric c:\import> python -c "import Numeric; print 'OK!'" OK! c:\import> echo raise Exception("Not OK! Local version") > Numeric\__init__.py c:\import> python -c "import Numeric;print 'OK!'" Traceback (most recent call last): File "", line 1, in ? File "Numeric\__init__.py", line 1, in ? raise Exception("Not OK! Local version") Exception: Not OK! Local version c:\import> del Numeric\__init__.py c:\import>python -c "import Numeric;print 'OK!'" Traceback (most recent call last): File "", line 1, in ? File "c:\python24\lib\site-packages\PIL\__init__.py", line 1, in ? # Exception: Not OK! Local version [authors note] What??? This was imported from Numeric\__init__.pyc c:\import> del Numeric\__init__.pyc c:\import> python -c "import Numeric;print 'OK!'" OK! The the actual example is more like this: c:\ImageD11> python setup.py build --compiler=mingw32 install ... c:\ImageD11>c:\python24\scripts\ImageD11_gui.py ... ImportError: can't import name closest c:\ImageD11> cd .. c:\> c:\python24\scripts\ImageD11_gui.py ...and the gui runs!! ... Given that the script resides in $python\scripts I sort of expect it to avoid tripping over some local and irrelevant file. From hat at se-126.se.wtb.tue.nl Fri Jun 2 12:55:10 2006 From: hat at se-126.se.wtb.tue.nl (A.T.Hofkamp) Date: Fri, 02 Jun 2006 12:55:10 +0200 Subject: Import Issue References: <1149230536.375190.12150@c74g2000cwc.googlegroups.com> Message-ID: On 2006-06-02, praveenkumar.117 at gmail.com wrote: > Hi all, > After doing import file i am updating that file. Later i am > accessing a dictionary contained in that > file. Eventhough changes are reflected in the file... When i > access a dictionary those changes are > not there. I believe that it is accessing from the object > file that is created when i did import at > the start of the script. I will be kind enough if somebody > suggest solution to this problem. The easiest suggestion I can make is "don't do that". An import statement is intended for importing static Python code, not for importing dynamic data such as dictionaries that you update while running. Your application is much easier to understand if you keep Python code and data in seperate files. For this, there are several options: A. If you stick to Python syntax of your data, you can load such files with 'open' and 'read', followed by 'eval' fp = open('datafile','r') datatext = fp.read() fp.close() print eval datatext B. If you don't care about accessing the data outside Python, you can use the pickle module to load and save the data. (please read http://docs.python.org/lib/module-pickle.html for details). C. Last but not least, you can define your own data format, and write custom load and save routines for accessing the data file. This approach is highly flexible, but it does cost effort to write the routines. Hope this answer your question, Albert From antroy at gmail.com Fri Jun 2 13:08:03 2006 From: antroy at gmail.com (Ant) Date: 2 Jun 2006 04:08:03 -0700 Subject: Selection in Tkinter Text widget. Message-ID: <1149246483.809582.8310@i39g2000cwa.googlegroups.com> Hi all, I have been trying to select text in a Text widget programmatically. I have been trying the following minimal example: #================================= from Tkinter import * def showgui(): win = Tk() area = Text(win, width = 50, height = 20) area.pack() new = """Lots of text here and here and here...""" area.insert("1.0", new) area.tag_add(SEL, "1.0", END) win.mainloop() if __name__ == "__main__": showgui() #================================== The area.tag_add(...) line should - from what I have read in Frederik's Intro to Tkinter guide - select all of the text in the text area. It doesn't however... Does anyone have any idea how to get this to work? Or tell me what I am doing wrong. Cheers, -- Ant... From maric at aristote.info Fri Jun 2 13:22:14 2006 From: maric at aristote.info (Maric Michaud) Date: Fri, 2 Jun 2006 13:22:14 +0200 Subject: Import Issue In-Reply-To: <1149230536.375190.12150@c74g2000cwc.googlegroups.com> References: <1149230536.375190.12150@c74g2000cwc.googlegroups.com> Message-ID: <200606021322.15743.maric@aristote.info> Le Vendredi 02 Juin 2006 08:42, praveenkumar.117 at gmail.com a ?crit?: > Hi all, > After doing import file i am updating that file. Later i am > accessing a dictionary contained in that > file. Eventhough changes are reflected in the file... When i > access a dictionary those changes are > not there. I believe that it is accessing from the object > file that is created when i did import at > the start of the script. I will be kind enough if somebody > suggest solution to this problem. Read in the doc the reload builtin description to understand what happens. But as Albert said before, don't do that ! -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From fredrik at pythonware.com Fri Jun 2 13:32:14 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 2 Jun 2006 13:32:14 +0200 Subject: import confused by contents of working directory References: <1149244708.049852.153980@i39g2000cwa.googlegroups.com> Message-ID: "Jon" wrote: > Would somebody please explain how to know what is going on when an > import statement is ambiguous? there is no ambiguity: python searches through a list of directories, in a given order. the list is stored in the sys.path list, which you can inspect and modify freely. also see the section "The Module Search Path" in the Modules chapter in the tutorial: http://pytut.infogami.com/node8.html > If the interpreter has several choices about what to import then which one is > chosen? the first one on the path. From iainking at gmail.com Fri Jun 2 13:30:55 2006 From: iainking at gmail.com (Iain King) Date: 2 Jun 2006 04:30:55 -0700 Subject: shuffling elements of a list In-Reply-To: References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> <1149051212.139046.155340@c74g2000cwc.googlegroups.com> Message-ID: <1149247855.487864.124540@i39g2000cwa.googlegroups.com> David C. Ullrich wrote: > On 30 May 2006 21:53:32 -0700, "greenflame" > wrote: > > That's DSU for _sorting_ a list. I read about this, thought > it was pretty neat. I thought that the fact that you > could use the same trick for _shuffling_ a list was > my idea, gonna make me rich and famous. I guess I'm > not the only one who thought of it. Anyway, you can > use DSU to _shuffle_ a list by decorating the list > with random numbers. > > In fairly old-fashioned Python: > > from random import random > > def shuffle(data): > decorated = map(lambda x: (random(), x), data) > decorated.sort() > return map(lambda x: x[1], decorated) > > print shuffle(range(10)) > > This prints > > [4, 2, 7, 8, 9, 3, 5, 1, 6, 0] > > . Seems kinda neat - I have no idea how the efficiency > compares with the standard sort of "bubble shuffle" > you were trying to use in your OP, but the point is > that various off-by-one errors simply don't come up. > > (The same thing in extremely awful Python, in case > you're mystified by map and lambda: > > from random import random > > def shuffle(data): > decorated = [] > for x in data: > decorated.append((random(), x)) > decorated.sort() > res = [] > for x in decorated: > res.append(x[1]) > return res > > .) or in nicer python, but still when you're mysitified by map and lambda (like me): def shuffle(data): decorated = [(random(), x) for x in data] decorated.sort() return [x[1] for x in decorated] or shorter but possible less readable (and only in 2.4+): def shuffle(data): return [y[1] for y in sorted([(random(), x) for x in data])] Iain From jes at nl.demon.net Fri Jun 2 13:44:33 2006 From: jes at nl.demon.net (Jim Segrave) Date: Fri, 02 Jun 2006 11:44:33 -0000 Subject: grouping a flat list of number by range References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> <1149201416.196975.123370@c74g2000cwc.googlegroups.com> <447F79C9.6080407@lexicon.net> <1149232358.817706.92680@j55g2000cwa.googlegroups.com> Message-ID: <12809513gd23kc1@corp.supernews.com> In article <1149232358.817706.92680 at j55g2000cwa.googlegroups.com>, Paddy wrote: > >John Machin wrote: >> On 2/06/2006 8:36 AM, Paddy wrote: > >> >> Oh the siren call of every new feature in the language! >> enumerate() just to get a first-time test, and then botch it?? >> >> Read the following; the replacement version uses a simple old-fashioned >> inelegant flag, works with an empty sequence, and doesn't depend on the >> input being sliceable or indexable. >> >> HTH, >> John >> > >Thanks, un-botchable John. What if the poster doesn't send a null list? >What if the correct result for a null list is "spam"; or an exception? >What if.... ... we toned down the language? I'd still rate Ben Cartwright's solution as the best. The one I posted tried to do the same, but I didn't see the right way to iterate over the supplied list inside the function, wheras he did. It's short, simple and correct. If you really wanted to return 'spam' or an exception in his solution, it's a simple if statement at the start of the function. -- Jim Segrave (jes at jes-2.demon.nl) From __peter__ at web.de Fri Jun 2 13:50:46 2006 From: __peter__ at web.de (Peter Otten) Date: Fri, 02 Jun 2006 13:50:46 +0200 Subject: shuffling elements of a list References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> <1149051212.139046.155340@c74g2000cwc.googlegroups.com> <1149247855.487864.124540@i39g2000cwa.googlegroups.com> Message-ID: Iain King wrote: > or shorter but possible less readable (and only in 2.4+): > > def shuffle(data): > return [y[1] for y in sorted([(random(), x) for x in data])] sorted() and list.sort() will happily accept a key function argument and then do the decorating/undecorating for you: >>> from random import random >>> def key(item): return random() ... >>> def shuffled(items): ... return sorted(items, key=key) ... >>> shuffled(range(10)) [6, 5, 3, 4, 8, 9, 0, 7, 1, 2] > or in nicer python, but still when you're mysitified by map and lambda > (like me): Turning the key() function into a lambda is left as an exercise :-) Peter From slawomir.nowaczyk.847 at student.lu.se Fri Jun 2 14:11:58 2006 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Fri, 02 Jun 2006 14:11:58 +0200 Subject: An oddity in list comparison and element assignment In-Reply-To: <1hg9pbo.1oem3vh1ryksipN%aleax@mac.com> References: <1hg9pbo.1oem3vh1ryksipN%aleax@mac.com> Message-ID: <20060602140630.FC41.SLAWOMIR.NOWACZYK.847@student.lu.se> On Thu, 01 Jun 2006 19:16:16 -0700 aleax at mac.com (Alex Martelli) wrote: #> > What does "parallel mutations" mean? In particular, what should be the #> > results of each of the following three comparisons: #> > #> > x, y, z = [1],[1],[1] #> > a, b = [x,y], [y,z] #> > c, d = [[1],[1]], [[1],[1]] #> > a == b #> > c == d #> > a[0].remove(1) #> > b[0].remove(1) #> > a == b #> > #> > So, do I understand correctly that you would like first comparison #> > (a==b) to return "False" and second comparison (c==d) to return #> > "True"? #> #> I sure hope not, So do I, but that's how I understood Michaels' words... #> In fact, I'm starting to wonder if by Michaels' requirement ANY #> non-*IDENTICAL* containers (with non-identical mutable items) could #> EVER be deemed "equal". If he's arguing that "==" should mean #> exactly the same as "is", that's even crazier than I had gauged so #> far. I think he explicitly said that "is" doesn't fulfill his requirements either... but then, I am not sure as I do not understand what his requirements actually are (they seem to make some sense for immutable objects, but how should they generalise to mutable stuff I have no idea). PS. Thanks for explanation about Bank of America: I had no clue how it works in realty, it just had a good name ;) -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) Java is clearly an example of a MOP (money-oriented programming) -- Alexander Stepanov From fredrik at pythonware.com Fri Jun 2 14:17:48 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 2 Jun 2006 14:17:48 +0200 Subject: Selection in Tkinter Text widget. References: <1149246483.809582.8310@i39g2000cwa.googlegroups.com> Message-ID: "Ant" wrote: > I have been trying to select text in a Text widget programmatically. I > have been trying the following minimal example: > #================================= > from Tkinter import * > > def showgui(): > win = Tk() > > area = Text(win, width = 50, height = 20) > area.pack() > > new = """Lots of text here > and here > and here...""" > area.insert("1.0", new) > > area.tag_add(SEL, "1.0", END) area.focus_set() > win.mainloop() > > if __name__ == "__main__": > showgui() > #================================== > > The area.tag_add(...) line should - from what I have read in Frederik's > Intro to Tkinter guide - select all of the text in the text area. It > doesn't however... it does, but by default, the selection is only shown for widgets that has the key- board focus. if you add an explicit focus_set() call, you'll see the selection. From piet at cs.uu.nl Fri Jun 2 14:07:23 2006 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 02 Jun 2006 14:07:23 +0200 Subject: New to Python: Do we have the concept of Hash in Python? References: Message-ID: >>>>> "A.M" (AM) wrote: >AM> This is my 1st day that I am seriously diving into Python and I have >AM> to finish this application by the end of today. Are you serious? -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From m.yanowitz at kearfott.com Fri Jun 2 14:20:42 2006 From: m.yanowitz at kearfott.com (Michael Yanowitz) Date: Fri, 2 Jun 2006 08:20:42 -0400 Subject: Tkinter - changing existing Dialog? In-Reply-To: <20f4l3-nga.ln1@lairds.us> Message-ID: Thanks. That is what I was looking for. The configure command (as you and John pointed out), should do what I need. The first response of starting a new thread was not what I was looking for. Michael Yanowitz -----Original Message----- In article , Michael Yanowitz wrote: >Hello: > > > I have a Tkinter GUI Dialog with many buttons and labels and text >widgets. >What I would like to do is, can I: > >1) Disable/deactivate/hide a button, text widget that is already drawn (and > of course the opposite enable/activate/show it)? . . . import Tkinter root = Tkinter.Tk() def actions(): print "Someone pushed the button." b.configure(state = Tkinter.DISABLED) b = Tkinter.Button(root, text = "Push me", command = actions) b.pack() root.mainloop() From antroy at gmail.com Fri Jun 2 14:37:39 2006 From: antroy at gmail.com (Ant) Date: 2 Jun 2006 05:37:39 -0700 Subject: Selection in Tkinter Text widget. In-Reply-To: References: <1149246483.809582.8310@i39g2000cwa.googlegroups.com> Message-ID: <1149251859.630518.248760@y43g2000cwc.googlegroups.com> Fredrik Lundh wrote: ... > it does, but by default, the selection is only shown for widgets that has the key- > board focus. if you add an explicit focus_set() call, you'll see the selection. > > Perfect! Thanks Fredrik. Strange behaviour though (IMHO), that the selection is only shown if the widget has focus. I just tried adding another component to the test, and switching from widget to widget does indeed stop the selection showing! Cheers, -- Ant... From junkytownMAKNI at gmail.com Fri Jun 2 14:56:54 2006 From: junkytownMAKNI at gmail.com (SuperHik) Date: Fri, 02 Jun 2006 14:56:54 +0200 Subject: Tkinter: select multiple entries in Listbox widget? In-Reply-To: References: Message-ID: Rob Williscroft wrote: > Bernard Lebel wrote in news:mailman.6413.1149178158.27775.python- > list at python.org in comp.lang.python: > >> Hello, >> >> Is there an option or a way to allow the selection of multiple entries >> in the Listbox widget? I could not find any, and would like to allow >> the end user to select multiple entries. >> >> > > When configuring use: > > selectmode = "multiple" > > e.g.: > > import Tkinter as tk > > root = tk.Tk() > > a = tk.Listbox( root, selectmode = "multiple" ) > for i in range(10): > a.insert( i, str(i) + " item" ) > > a.pack() > root.mainloop() > > I found the answer here: > > http://www.python.org/doc/life-preserver/ClassListbox.html > > Though I had to guess the `= "multiple"` part. > > Rob. cool. never needed it so far but it's nice to know :D From buzzard at urubu.freeserve.co.uk Fri Jun 2 15:11:28 2006 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Fri, 02 Jun 2006 14:11:28 +0100 Subject: after del list , when I use it again, prompt 'not defined'.how could i delete its element,but not itself? In-Reply-To: <1149235087.256704.309360@g10g2000cwb.googlegroups.com> References: <1149235087.256704.309360@g10g2000cwb.googlegroups.com> Message-ID: <44803b20.0@entanet> python wrote: [snip] > > How could I keep the list1 not to change when remove list2's elements? > You can't when the names list1 and list2 refer to the same list. Try making list2 a copy of list1, list2 = list(list1) Duncan From xivulon at gmail.com Fri Jun 2 15:17:50 2006 From: xivulon at gmail.com (ago) Date: 2 Jun 2006 06:17:50 -0700 Subject: win32com: how to connect to a specific instance of a running object? In-Reply-To: References: Message-ID: <1149254270.790703.145700@j55g2000cwa.googlegroups.com> Thanks, after some further digging I hit something... The following seems to do the trick: import win32gui WINDOW_CLASS = 'XLMAIN' WINDOW_TITLE = 'Microsoft Excel - MySpreadsheet.xls' hwindow = win32gui.FindWindow(WINDOW_CLASS,WINDOW_TITLE) Now the next question is: how do I use the window-handle returned? I would like to work with a com object like the one returned by win32com.client.Dispatch('ExcelApplication'). Any hint? PS I could also use win32ui instead win32gui, in this case I get a window object instead of an handle. But I still do not know how to transform it into a nice pythoncom excel object. From florencio.cano at gmail.com Fri Jun 2 15:21:20 2006 From: florencio.cano at gmail.com (Florencio Cano) Date: Fri, 2 Jun 2006 15:21:20 +0200 Subject: Which exceptions are recommended to me handled? Message-ID: Hello, Is it recommended as a good programming practice to catch all exceptions and raise our own exceptions or let Python itself raise these kinds of exceptions? For example imagine a function that needs an integer and '34' is passed, this is ok because inside the function it uses int(variable) but if a 'hello' is passed it will raise a ValueError exception. Is it better to handle this exception or let Python raise directly ValueError and stop execution or what is recommended? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/python-list/attachments/20060602/0b3fc395/attachment.htm From brochu121 at gmail.com Fri Jun 2 15:29:19 2006 From: brochu121 at gmail.com (david brochu jr) Date: Fri, 2 Jun 2006 09:29:19 -0400 Subject: Tkinter Message-ID: <9583ed900606020629n6b54b522j117b521ca7ac616e@mail.gmail.com> Does anyone know how to get the value of the file selected when using tk_getOpenFile in Tkinter? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/python-list/attachments/20060602/e13aab64/attachment.html From junkytownMAKNI at gmail.com Fri Jun 2 15:32:19 2006 From: junkytownMAKNI at gmail.com (SuperHik) Date: Fri, 02 Jun 2006 15:32:19 +0200 Subject: after del list , when I use it again, prompt 'not defined'.how could i delete its element,but not itself? In-Reply-To: <1149236355.221540.136120@y43g2000cwc.googlegroups.com> References: <1149235087.256704.309360@g10g2000cwb.googlegroups.com> <1149236355.221540.136120@y43g2000cwc.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > python wrote: >> after del list , when I use it again, prompt 'not defined'.how could i >> delete its element,but not itself? > > This is a way: >>>> a = range(10) >>>> del a[:] or simply a = [] >>>> a > [] >>>> a.append(20) >>>> a > [20] > > Bye, > bearophile > From fredrik at pythonware.com Fri Jun 2 15:54:07 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 2 Jun 2006 15:54:07 +0200 Subject: Tkinter References: <9583ed900606020629n6b54b522j117b521ca7ac616e@mail.gmail.com> Message-ID: "david brochu jr" wrote: > Does anyone know how to get the value of the file selected when using > tk_getOpenFile in Tkinter? why not use the tkFileDialog module: http://www.pythonware.com/library/tkinter/introduction/x1164-data-entry.htm ? From claudio.grondi at freenet.de Fri Jun 2 16:08:25 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Fri, 02 Jun 2006 16:08:25 +0200 Subject: integer to binary... In-Reply-To: <1149197110.225383.107770@f6g2000cwb.googlegroups.com> References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> <1149197110.225383.107770@f6g2000cwb.googlegroups.com> Message-ID: mensanator at aol.com wrote: > nicolasg at gmail.com wrote: > >>does anyone know a module or something to convert numbers like integer >>to binary format ? >> >>for example I want to convert number 7 to 0111 so I can make some >>bitwise operations... >> >>Thanks > > > Use the gmpy module. > > >>>>import gmpy >>>>a = 14 >>>>b = 7 >>>>c = 8 > > >>>>help(gmpy.digits) > > Help on built-in function digits: > > digits(...) > digits(x[,base]): returns Python string representing x in the > given base (2 to 36, default 10 if omitted or 0); leading '-' > present if x<0, but no leading '+' if x>=0. x must be an mpz, > or else gets coerced into one. > > >>>>print gmpy.digits(a,2) > > 1110 > >>>>print gmpy.digits(b,2) > > 111 > >>>>print gmpy.digits(c,2) > > 1000 > > > >>>>help(gmpy.setbit) > > Help on built-in function setbit: > > setbit(...) > setbit(x,n,v=1): returns a copy of the value of x, with bit n set > to value v; n must be an ordinary Python int, >=0; v, 0 or !=0; > x must be an mpz, or else gets coerced to one. > > >>>>d = gmpy.setbit(c,1,1) >>>>print gmpy.digits(d,2) > > 1010 > > > > >>>>help(gmpy.scan1) > > Help on built-in function scan1: > > scan1(...) > scan1(x, n=0): returns the bit-index of the first 1-bit of x (that > is at least n); n must be an ordinary Python int, >=0. If no more > 1-bits are in x at or above bit-index n (which can only happen for > x>=0, notionally extended with infinite 0-bits), None is returned. > x must be an mpz, or else gets coerced to one. > > >>>>help(gmpy.scan0) > > Help on built-in function scan0: > > scan0(...) > scan0(x, n=0): returns the bit-index of the first 0-bit of x (that > is at least n); n must be an ordinary Python int, >=0. If no more > 0-bits are in x at or above bit-index n (which can only happen for > x<0, notionally extended with infinite 1-bits), None is returned. > x must be an mpz, or else gets coerced to one. > > >>>>print gmpy.scan1(a) > > 1 > >>>>print gmpy.scan1(b) > > 0 > >>>>print gmpy.scan1(c) > > 3 > >>>>print gmpy.scan1(d) > > 1 > >>>>print gmpy.scan0(a) > > 0 > >>>>print gmpy.scan0(b) > > 3 > >>>>print gmpy.scan0(c) > > 0 > >>>>print gmpy.scan0(d) > > 0 > > >>>>help(gmpy.popcount) > > Help on built-in function popcount: > > popcount(...) > popcount(x): returns the number of 1-bits set in x; note that > this is 'infinite' if x<0, and in that case, -1 is returned. > x must be an mpz, or else gets coerced to one. > > >>>>print gmpy.popcount(a) > > 3 > >>>>print gmpy.popcount(b) > > 3 > >>>>print gmpy.popcount(c) > > 1 > >>>>print gmpy.popcount(d) > > 2 > > > >>>>help(gmpy.hamdist) > > Help on built-in function hamdist: > > hamdist(...) > hamdist(x,y): returns the Hamming distance (number of bit-positions > where the bits differ) between x and y. x and y must be mpz, or > else > get coerced to mpz. > > >>>>print gmpy.hamdist(a,b) > > 2 > >>>>print gmpy.hamdist(a,c) > > 2 > >>>>print gmpy.hamdist(a,d) > > 1 > >>>>print gmpy.hamdist(b,c) > > 4 > >>>>print gmpy.hamdist(b,d) > > 3 > >>>>print gmpy.hamdist(c,d) > > 1 > For those digging deeper into this subject who are looking for speed, reading the past discussion on this newsgroup I was part of myself looking for fastest way of such integer to binary conversion can maybe be of interest: http://mail.python.org/pipermail/python-list/2006-January/319295.html (includes full source code of all compared approaches) Claudio From anthra.norell at tiscalinet.ch Fri Jun 2 16:14:36 2006 From: anthra.norell at tiscalinet.ch (Anthra Norell) Date: Fri, 2 Jun 2006 16:14:36 +0200 Subject: losing handles of open files References: <000c01c68558$a48a9680$0201a8c0@mcuf7> <877j40zext.fsf@benfinney.id.au> Message-ID: <001d01c6864e$e1498260$0201a8c0@mcuf7> ----- Original Message ----- From: "Ben Finney" To: Sent: Friday, June 02, 2006 12:30 AM Subject: Re: losing handles of open files > Please don't post non-text message bodies to discussion > forums. Message bodies should be plain text. > > "Anthra Norell" writes: > > > If a piece of code exits with an exception before it closes an open > > file, that file seems to remain locked, which is real pain in the > > butt > > You will want to examine the 'finally' clause, which is executed after > the 'try' suite regardless of exceptions. > > > > > You may also be interested in the 'with' statement, coming in Python > 2.5, which will be a more natural way of expressing this idiom. > > > > -- > \ "If nature has made any one thing less susceptible than all | > `\ others of exclusive property, it is the action of the thinking | > _o__) power called an idea" -- Thomas Jefferson | > Ben Finney > > -- > http://mail.python.org/mailman/listinfo/python-list Ben, Thank you very much for your input. I'm sorry about the text. I thought it was text. Could it have to do with the font? I am aware of the finally clause, though I just haven't met it face to face yet on the learning curve yet. Guess the time has come. I shall study your references. Frederic From jjlee at reportlab.com Fri Jun 2 00:26:34 2006 From: jjlee at reportlab.com (John J. Lee) Date: Thu, 01 Jun 2006 22:26:34 GMT Subject: ANN: ReportLab PDF Library version 2.0 and 1.21 released Message-ID: ReportLab are proud to announce not one but two major releases of our PDF document generation framework. The ReportLab PDF Toolkit lets you generate rich flowing documents in PDF from dynamic data, complete with multiple columns, tables and charts, at extremely high speeds; and to generate charts and data graphics in PDF and bitmap formats. It was first released in mid-2000 and the previous stable release, 1.20, was in late 2004. The 2.0 release includes many new features, and works with Unicode or UTF8 input throughout. This simplifies many things but may break old code that uses non-ASCII input. It should be trivial to upgrade your app using the Python codecs package, which now includes codecs for most of the world's languages. http://www.reportlab.org/whatsnew_2_0.html We have also produced a 1.21 release with a number of minor enhancements and bug fixes since 1.20, and with the old character handling behaviour. This should provide a safe upgrade for all existing users. http://www.reportlab.org/whatsnew_1_21.html ReportLab's commercial products (Report Markup Language, Diagra and PageCatcher) also have their own 2.0 and 1.21 releases and are documented on http://developer.reportlab.com/index.html. Open source users are encouraged to review the RML examples and test cases, which provide very clear examples of what's possible with the underlying Python objects. Best regards, John From stefan.behnel-n05pAM at web.de Fri Jun 2 12:53:29 2006 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Fri, 02 Jun 2006 12:53:29 +0200 Subject: [ANN] lxml 1.0 released Message-ID: Hallo everyone, I have the honour to announce the availability of lxml 1.0. http://codespeak.net/lxml/ It's downloadable from cheeseshop: http://cheeseshop.python.org/pypi/lxml """ lxml is a Pythonic binding for the libxml2 and libxslt libraries. It provides safe and convenient access to these libraries using the ElementTree API. It extends the ElementTree API significantly to offer support for XPath, RelaxNG, XML Schema, XSLT, C14N and much, much more. Its goals are: * Pythonic API. * Documented. http://codespeak.net/lxml/#documentation * FAST! http://codespeak.net/lxml/performance.html * Use Python unicode strings in API. * Safe (no segfaults). * No manual memory management! (as opposed to the official libxml2 Python bindings) """ While the list of features added since the last beta version (1.0.beta) is rather small, this version contains a large number of bug fixes found by various users and testers. Thank you all for your help! Stefan Features added since 0.9.2: * Element.getiterator() and the findall() methods support finding arbitrary elements from a namespace (pattern {namespace}*) * Another speedup in tree iteration code * General speedup of Python Element object creation and deallocation * Writing C14N no longer serializes in memory (reduced memory footprint) * PyErrorLog for error logging through the Python logging module * element.getroottree() returns an ElementTree for the root node of the document that contains the element. * ElementTree.getpath(element) returns a simple, absolute XPath expression to find the element in the tree structure * Error logs have a last_error attribute for convenience * Comment texts can be changed through the API * Formatted output via pretty_print keyword to serialization functions * XSLT can block access to file system and network via XSLTAccessControl * ElementTree.write() no longer serializes in memory (reduced memory footprint) * Speedup of Element.findall(tag) and Element.getiterator(tag) * Support for writing the XML representation of Elements and ElementTrees to Python unicode strings via etree.tounicode() * Support for writing XSLT results to Python unicode strings via unicode() * Parsing a unicode string no longer copies the string (reduced memory footprint) * Parsing file-like objects now reads chunks rather than the whole file (reduced memory footprint) * Parsing StringIO objects from the start avoids copying the string (reduced memory footprint) * Read-only 'docinfo' attribute in ElementTree class holds DOCTYPE information, original encoding and XML version as seen by the parser * etree module can be compiled without libxslt by commenting out the line include "xslt.pxi" near the end of the etree.pyx source file * Better error messages in parser exceptions * Error reporting now also works in XSLT * Support for custom document loaders (URI resolvers) in parsers and XSLT, resolvers are registered at parser level * Implementation of exslt:regexp for XSLT based on the Python 're' module, enabled by default, can be switched off with 'regexp=False' keyword argument * Support for exslt extensions (libexslt) and libxslt extra functions (node-set, document, write, output) * Substantial speedup in XPath.evaluate() * HTMLParser for parsing (broken) HTML * XMLDTDID function parses XML into tuple (root node, ID dict) based on xml:id implementation of libxml2 (as opposed to ET compatible XMLID) Bugs fixed since 0.9.2: * Memory leak in Element.__setitem__ * Memory leak in Element.attrib.items() and Element.attrib.values() * Memory leak in XPath extension functions * Memory leak in unicode related setup code * Element now raises ValueError on empty tag names * Namespace fixing after moving elements between documents could fail if the source document was freed too early * Setting namespace-less tag names on namespaced elements ('{ns}t' -> 't') didn't reset the namespace * Unknown constants from newer libxml2 versions could raise exceptions in the error handlers * lxml.etree compiles much faster * On libxml2 <= 2.6.22, parsing strings with encoding declaration could fail in certain cases * Document reference in ElementTree objects was not updated when the root element was moved to a different document * Running absolute XPath expressions on an Element now evaluates against the root tree * Evaluating absolute XPath expressions (/*) on an ElementTree could fail * Crashes when calling XSLT, RelaxNG, etc. with uninitialized ElementTree objects * Memory leak when using iconv encoders in tostring/write * Deep copying Elements and ElementTrees maintains the document information * Serialization functions raise LookupError for unknown encodings * Memory deallocation crash resulting from deep copying elements * Some ElementTree methods could crash if the root node was not initialized (neither file nor element passed to the constructor) * Element/SubElement failed to set attribute namespaces from passed attrib dictionary * tostring() now adds an XML declaration for non-ASCII encodings * tostring() failed to serialize encodings that contain 0-bytes * ElementTree.xpath() and XPathDocumentEvaluator were not using the ElementTree root node as reference point * Calling document('') in XSLT failed to return the stylesheet From chris at kateandchris.net Fri Jun 2 16:33:06 2006 From: chris at kateandchris.net (Chris Lambacher) Date: Fri, 2 Jun 2006 10:33:06 -0400 Subject: Python for Visual Basic or C# programmers In-Reply-To: References: Message-ID: <20060602143305.GA7371@kateandchris.net> On Fri, Jun 02, 2006 at 10:26:28AM +0200, Laurent Pointal wrote: > A.M a ?crit : > > Hi, > > > > > > > > I am trying to find the equivalent functions such as vb's str or asc in > > Python. Is there any resource that help me to find these kinds of functions > > in Python faster? > > > > I've written the PQRC for that purpose: > http://www.limsi.fr/Individu/pointal/python/pqrc/ > > There is also the Python Quick reference series: http://rgruet.free.fr/#QuickRef > > A+ > > Laurent. > -- > http://mail.python.org/mailman/listinfo/python-list From bussieremaillist at gmail.com Fri Jun 2 16:57:30 2006 From: bussieremaillist at gmail.com (bussiere maillist) Date: Fri, 2 Jun 2006 16:57:30 +0200 Subject: gadfly error gadfly instance has no attribute 'execute' Message-ID: <8a8f62c80606020757g328bb37dlbdbf3d63bf379e69@mail.gmail.com> here is the error i've get : Traceback (most recent call last): File "D:\Programmation\pitney\pitney.py", line 13, in ? connection.execute('create table personne(nom varchar)') AttributeError: gadfly instance has no attribute 'execute' i'am under windows and i still haven't found the error here is my code : import csv,gadfly,fileinput,glob, string, sys, os,unicodedata print "que voulez vous faire ?\n" fichA=raw_input("Entrez le nom du fichier a importer : ") cr = csv.reader(open(fichA),delimiter=";") connection = gadfly.gadfly() connection.startup('pitney','D:\Programmation\pitney\') cursor = connection.cursor() connection.execute('create table personne(nom varchar)') cursor.execute("insert into personne(nom) values('bussiere')") connection.commit() cursor.execute('select * from personne') print cursor.fetchall() compteur = 0 for row in cr: print row[0],row[1] compteur += 1 print "Dead Parrot" regards Bussiere -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/python-list/attachments/20060602/63c59e1f/attachment.htm From xivulon at gmail.com Fri Jun 2 16:57:33 2006 From: xivulon at gmail.com (ago) Date: 2 Jun 2006 07:57:33 -0700 Subject: win32com: how to connect to a specific instance of a running object? In-Reply-To: <1149254270.790703.145700@j55g2000cwa.googlegroups.com> References: <1149254270.790703.145700@j55g2000cwa.googlegroups.com> Message-ID: <1149260253.337452.65770@c74g2000cwc.googlegroups.com> The other approach I tried (as suggested by Tim, thanks) involves browsing the ROT. import pythoncom SPREADSHEET_NAME = r'\MySpreadsheet.xls' lenstr = len(SPREADSHEET_NAME) obj = None rot = pythoncom.GetRunningObjectTable() rotenum = rot.EnumRunning() while True: monikers = rotenum.Next() if not monikers: break ctx = pythoncom.CreateBindCtx(0) name = monikers[0].GetDisplayName(ctx, None); if name[-lenstr:] == SPREADSHEET_NAME: obj = rot.GetObject(monikers[0]) break The obj I get is a PyIUnknown... How do I use it? From antroy at gmail.com Fri Jun 2 17:07:33 2006 From: antroy at gmail.com (Ant) Date: 2 Jun 2006 08:07:33 -0700 Subject: How do you practice Python? In-Reply-To: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> References: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> Message-ID: <1149260853.743979.32270@g10g2000cwb.googlegroups.com> > In our field, we don't always get to program in the language we'd like For sure! > to program. So... how do you practice Python in this case? Say you're > doing J2EE right now. How do you practice Python to keep your skills > sharp? Well, we have to use J2EE at work. I keep my Python skills going by playing the puzzles like the PythonChallenge you mentioned and the Maths Challenge Euler project (http://mathschallenge.net/index.php?section=project) They are good for getting the Python idioms and shortcuts nailed, such as list comprehensions, generators etc that aren't available in Java. I also use Python almost exclusively at home for my website, Wiki, Photo gallery etc - all of which I hand rolled partly for the experience, and partly to get them exactly the way I want them :-) At work I use Python for all my scripting needs. I also use it to automate running through our web-applications for test purposes, using a framework I wrote around the urllib2 module. So, there are plenty of opportunities to use it if you keep your eyes open. Unfortunately for me, using Python so much has made using J2EE very painful. Not so good seeing as it's my day job! From johnjsal at NOSPAMgmail.com Fri Jun 2 17:15:34 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 02 Jun 2006 15:15:34 GMT Subject: integer to binary... In-Reply-To: <1149197110.225383.107770@f6g2000cwb.googlegroups.com> References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> <1149197110.225383.107770@f6g2000cwb.googlegroups.com> Message-ID: mensanator at aol.com wrote: > Use the gmpy module. Yes, it's good. :) From siona at chiark.greenend.org.uk Fri Jun 2 17:14:56 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 02 Jun 2006 16:14:56 +0100 (BST) Subject: integer to binary... References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> <127ugf9jgu7av18@corp.supernews.com> <1149190940.548582.27200@h76g2000cwa.googlegroups.com> Message-ID: <0Oh*8vbir@news.chiark.greenend.org.uk> Tim Chase wrote: >bitCount = len([c for c in "01001010101" if c=="1"]) bitCount = "01001010101".count("1") -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From siona at chiark.greenend.org.uk Fri Jun 2 17:21:04 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 02 Jun 2006 16:21:04 +0100 (BST) Subject: New to Python: Do we have the concept of Hash in Python? References: <1149182265.257263.159210@f6g2000cwb.googlegroups.com> Message-ID: gregarican wrote: >I came from using Ruby about a year or so [ ... ] That's an interesting way round. Why did you consider Python if you already knew Ruby, and which is now your preferred language? (I've no interest in learning Ruby, but from what I've seen of it I similarly can't imagine what would motivate me to learn Python.) -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From siona at chiark.greenend.org.uk Fri Jun 2 17:30:22 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 02 Jun 2006 16:30:22 +0100 (BST) Subject: Using print instead of file.write(str) References: Message-ID: <2Iq*Jzbir@news.chiark.greenend.org.uk> A.M wrote: >I found print much more flexible that write method. "more flexible"? More convenient, yes. More powerful, maybe. But I don't see more flexible. Everything print can to stdout.write() can do. The reverse isn't true. eg (this appears to be a FAQ on this group, although I can't find it in the FAQ): for x in range(10): sys.stdout.write(str(x)) to print: 0123456789 -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From bnblazer at gmail.com Fri Jun 2 17:35:05 2006 From: bnblazer at gmail.com (Brian) Date: 2 Jun 2006 08:35:05 -0700 Subject: Are there something like "Effective Python"? In-Reply-To: <1149236138.364915.189890@i40g2000cwc.googlegroups.com> References: <1149224468.481470.74580@i39g2000cwa.googlegroups.com> <1149229055.088793.89010@i39g2000cwa.googlegroups.com> <1149236138.364915.189890@i40g2000cwc.googlegroups.com> Message-ID: <1149262505.634173.126610@h76g2000cwa.googlegroups.com> You might want to give this site a look: http://www.livewires.org.uk/python/ From brian at sweetapp.com Fri Jun 2 17:54:59 2006 From: brian at sweetapp.com (Brian Quinlan) Date: Fri, 02 Jun 2006 17:54:59 +0200 Subject: Sampling a population Message-ID: <44805F53.6090409@sweetapp.com> This is less a Python question and more a optimization/probability question. Imaging that you have a list of objects and there frequency in a population e.g. lst = [(a, 0.01), (b, 0.05), (c, 0.50), (d, 0.30), (e, 0.04), (f, 0.10)] and you want to drawn n items from that list (duplicates allowed), with that probability distribution. The fastest algorithm that I have been able to devise for doing so is: O(n * log(len(lst))). Can anyone think or a solution with a better time complexity? If not, is there an obviously better way to do this (assuming n is big and the list size is small). Here is the code: from random import random from bisect import bisect def draw(n, lst): ps = [] last = 0 for p in lst: ps.append(last + p) last += p # ps = [0.01, 0.06, 0.56, 0.86, 0.90, 1.00] chosen = [0] * len(lst) # track frequency for i in range(n): r = random() chosen[bisect(ps, r)] += 1 # binary search and increment result = [] # rescale probability based on frequency for c in chosen: result.append(float(c) / n) return result lst = [0.01, 0.05, 0.50, 0.30, 0.04, 0.10] print draw(10000, lst) From matth at gmx.net Fri Jun 2 18:08:21 2006 From: matth at gmx.net (Matthieu Pichaud) Date: Fri, 2 Jun 2006 18:08:21 +0200 Subject: Package Message-ID: I have a problem organizing my programs in packages and subpackages. I use python.2.3.3 I built a test structure to try to understand how it worked: /test /test/__init__.py (containing: __all__=['test1']) /test/test1/ /test/test1/__init__.py (containing: __all__=['test2']) /test/test1/test2/ /test/test1/test2/__init__.py (containing: __all__=['test3']) /test/test1/test2/test3.py (containing: print 'test3') Then I run: >>> from test import * >>> test1 >>> test2 Traceback (most recent call last): File "", line 1, in ? NameError: name 'test2' is not defined So it seems that I am very limited in the number of subpackages I can create. Is it normal? Am I silly organizing my programs like that? Thanks for your help! Matth From edreamleo at charter.net Fri Jun 2 18:14:52 2006 From: edreamleo at charter.net (Edward K. Ream) Date: Fri, 2 Jun 2006 11:14:52 -0500 Subject: Best Python Editor References: Message-ID: <7uZfg.4$5t3.2@fe07.lga> I like scite for small tasks, Leo for larger tasks and python scripting. Leo's script buttons are something probably no other tool has: http://webpages.charter.net/edreamleo/customizing.html#creating-script-buttons Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From alanalan at newsgroup.nospam Fri Jun 2 18:16:21 2006 From: alanalan at newsgroup.nospam (A.M) Date: Fri, 2 Jun 2006 12:16:21 -0400 Subject: New to Python: Do we have the concept of Hash in Python? References: <1149182265.257263.159210@f6g2000cwb.googlegroups.com> Message-ID: "Sion Arrowsmith" wrote in message news:eYk*yxbir at news.chiark.greenend.org.uk... > gregarican wrote: >>I came from using Ruby about a year or so [ ... ] > > That's an interesting way round. Why did you consider Python if > you already knew Ruby, and which is now your preferred language? > (I've no interest in learning Ruby, but from what I've seen of it > I similarly can't imagine what would motivate me to learn Python.) > > -- > \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ > ___ | "Frankly I have no feelings towards penguins one way or the > other" > \X/ | -- Arthur C. Clarke > her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump My decision wasn't based on which language I am most comfortable with. I can do the same application in Java in one hour. We are looking for a scripting language to use across our organization. This is a strategic decision. Out 1st choice is Python, the second one is Perl and the last one is Ruby. Yesterday I proof that Python is way to go. The programming language aspects of Ruby is a brilliant, but the language itself is not everything. I encountered some problem with Ruby and I found it is not there yet. Here is some of problems I have with ruby: (consider the fact that it is my personal opinion) 1) Ruby community feel that there is strong database access support. I personally didn't find DBI distribution and documentation very organized and at the production level. For example, DBI:OCI8 is at experimental state. http://www.jiubao.org/ruby-oci8/ Oracle data access support is very important for me and DBI:OCI8 is the only way you can get data from Oracle stored procedures. 2) Komodo (my favorite scripting IDE) crashes when I debug certain type of Ruby scripts. Moreover there is no ActiveRuby from ActiveState **yet**. 3) You can find lots of excellent Python books from OREILLY. You don't have much option for Ruby **yet**. 4) Ruby became famous because of Rails. Rails is a great idea, but I am so focused on ASP.NET and J2EE and I am going to stay there. Rails doesn't have a production level support for IIS. So I am not very interested in Rails. In essence, Ruby language is the best, but Ruby platform is too young for me. I'll give Ruby another two years and come back to it again. I found the Python language quite powerful and easy. With mature and strong community support. From dannycolligan at gmail.com Fri Jun 2 18:58:36 2006 From: dannycolligan at gmail.com (dannycolligan at gmail.com) Date: 2 Jun 2006 09:58:36 -0700 Subject: os.chdir doesn't accept variables sometimes Message-ID: <1149267516.348440.60290@u72g2000cwu.googlegroups.com> I have a strange problem with os.chdir... here is my script that I am using to edit the filenames of my music library: #!/usr/bin/python from os import * chdir("/home/chainlynx/Desktop/Music") for artist in listdir(getcwd()): print "===ARTIST: "+artist chdir(artist) for album in listdir(getcwd()): print "---ALBUM: "+album print "CWD: " + getcwd() chdir(album) ######ERROR ON THIS LINE for string in listdir(album): print "-SONG "+ string if string[-3:] == "mp3": print "CONVERTING "+string+" to "+string[:string.index(".")]+".mp3" # string = string[:string.index(".")]+".mp3" The dummy file structure that I set up to run this: chainlynx at cronus:~/Desktop/Music$ find . . ./AAAAA ./AAAAA/Album1 ./AAAAA/Album2 ./AAAAA/Album3 ./AAAAA/Album3/song1.m4a.x.mp3 ./BBBBB ./CCCCC ./CCCCC/Albummmmm ./CCCCC/Albummmmm/asdfasdf.ogg ./CCCCC/Albummmmm/blah.m4a.wav.mp3 ./CCCCC/Albummmmm/good.mp3 The error I get: chainlynx at cronus:~/workspace/PyTest/src/pypack$ python __init__.py ===ARTIST: AAAAA ---ALBUM: Album1 CWD: /home/chainlynx/Desktop/Music/AAAAA Traceback (most recent call last): File "/home/chainlynx/workspace/PyTest/src/pypack/__init__.py", line 12, in ? for string in listdir(album): OSError: [Errno 2] No such file or directory: 'Album1' Does anyone know why this is choking? Clearly, because of the second chdir(), chdir() can accept variables like this... what am I doing wrong? Thanks in advance, Danny P.S. Bonus points: is there any way to bash shell script this on the command line instead (recursively)? From steven.bethard at gmail.com Fri Jun 2 19:01:43 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 02 Jun 2006 11:01:43 -0600 Subject: grouping a flat list of number by range In-Reply-To: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> Message-ID: joh12005 at yahoo.fr wrote: > i'm looking for a way to have a list of number grouped by consecutive > interval, after a search, for example : > > [3, 6, 7, 8, 12, 13, 15] > > => > > [[3, 4], [6,9], [12, 14], [15, 16]] Know your itertools. From the examples section[1]: """ # Find runs of consecutive numbers using groupby. The key to the # solution is differencing with a range so that consecutive numbers all # appear in same group. >>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28] >>> for k, g in groupby(enumerate(data), lambda (i,x):i-x): ... print map(operator.itemgetter(1), g) ... [1] [4, 5, 6] [10] [15, 16, 17, 18] [22] [25, 26, 27, 28] """ So I think something like this should work: >>> import itertools >>> def intervals(numbers): ... def key((i, n)): ... return i - n ... for key, group in itertools.groupby(enumerate(numbers), key): ... group = list(group) ... _, first_n = group[0] ... _, last_n = group[-1] ... yield first_n, last_n + 1 ... >>> list(intervals([3, 6, 7, 8, 12, 13, 15])) [(3, 4), (6, 9), (12, 14), (15, 16)] If you really need lists instead of tuples, just put brackets around the terms in the yield statement. [1] http://docs.python.org/lib/itertools-example.html STeVe From aahz at pythoncraft.com Fri Jun 2 19:07:10 2006 From: aahz at pythoncraft.com (Aahz) Date: 2 Jun 2006 10:07:10 -0700 Subject: An oddity in list comparison and element assignment References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1149194434.528648.148860@u72g2000cwu.googlegroups.com> <1hg9onn.p25evr18a09f9N%aleax@mac.com> Message-ID: In article <1hg9onn.p25evr18a09f9N%aleax at mac.com>, Alex Martelli wrote: > >Just to share some tidbits (about which, as an Italian now living >between San Francisco and San Jose, I'm sort of proud of...!-)...: > >Bank of America is a private bank, founded in San Francisco more than >100 years ago by an Italian-American guy (Amadeo Giannini, born in San >Jose, CA, but to Italian-born parents) as "Bank of Italy", then renamed >in 1930 in part because the Italian State bank "Banca d'Italia" >objected. It rose to prominence right after the SF earthquake of 100 >years ago, by opening and staffing a temporary branch to ensure >depositors could access their money when they most needed it, while most >other banks were staying closed. Except, of course, that BofA doesn't exist anymore. Oh, the *name* does, but what's now called BofA is simply the current name of the bank that acquired BofA. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I saw `cout' being shifted "Hello world" times to the left and stopped right there." --Steve Gonedes From aahz at pythoncraft.com Fri Jun 2 19:11:42 2006 From: aahz at pythoncraft.com (Aahz) Date: 2 Jun 2006 10:11:42 -0700 Subject: Are there something like "Effective Python"? References: <1149224468.481470.74580@i39g2000cwa.googlegroups.com> Message-ID: In article <1149224468.481470.74580 at i39g2000cwa.googlegroups.com>, Mike Meng wrote: > > I just finished reading Learning Python 3rd ed, and am doing my >first Python application, which retrieves and process text and XML >documents from Web. Python helped me to write the application in a few >hours, I'm very happy with its productivity. But the performance is not >satisfactory. I decide to optimized it in Python before trying C/C++ >extensions. But I don't know Python much and have no clu to tune my >program. Also, I don't know what Pythonist's preferred styles. Are >there any books/documents which play the similar role for Python as >'Effective C++' does for C++? That's my fault. I'm technically still under contract to write _Effective Python_, but it has proven much more difficult to write than I expected. (Not in the sense of difficulty finding material, but in sitting down and *writing*.) I actually brought in David Goodger as co-author and we still haven't been able to make progress. :-( Right now, I'm finishing up _Python for Dummies_ (which is mostly being written by Stef -- I provide the technical expertise and editing), and after a suitable resting time, we'll see if we can get back on track with _Effective Python_ -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I saw `cout' being shifted "Hello world" times to the left and stopped right there." --Steve Gonedes From onurb at xiludom.gro Fri Jun 2 19:11:24 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 02 Jun 2006 19:11:24 +0200 Subject: Package In-Reply-To: References: Message-ID: <448071b0$0$11225$636a55ce@news.free.fr> Matthieu Pichaud wrote: > I have a problem organizing my programs in packages and subpackages. > > I use python.2.3.3 > I built a test structure to try to understand how it worked: > > /test > /test/__init__.py (containing: __all__=['test1']) > /test/test1/ > /test/test1/__init__.py (containing: __all__=['test2']) > /test/test1/test2/ > /test/test1/test2/__init__.py (containing: __all__=['test3']) > /test/test1/test2/test3.py (containing: print 'test3') > > Then I run: >>>> from test import * >>>> test1 > >>>> test2 > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'test2' is not defined > So it seems that I am very limited in the number of subpackages I can > create. Not at all. > Is it normal? Yes : when you have nested namespaces, it won't magically become a flat namespace. There's a mostly clear documention on this in the official Python tutorial. > Am I silly organizing my programs like that? Dunno - it depends on the program. But still: python -c "import this" | grep nested HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From maxerickson at gmail.com Fri Jun 2 19:19:03 2006 From: maxerickson at gmail.com (Max Erickson) Date: Fri, 2 Jun 2006 17:19:03 +0000 (UTC) Subject: Package References: Message-ID: I'm no expert, but your post made me curious. It appears that __all__ has the effect of ensuring that from test import * picks up test1, but doesn't go any further than that. from test.test1.test2 import * should cause test3 to be imported. max From buzzard at urubu.freeserve.co.uk Fri Jun 2 19:19:32 2006 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Fri, 02 Jun 2006 18:19:32 +0100 Subject: Sampling a population In-Reply-To: References: Message-ID: <44807544.0@entanet> Brian Quinlan wrote: > This is less a Python question and more a optimization/probability > question. Imaging that you have a list of objects and there frequency in > a population e.g. > > lst = [(a, 0.01), (b, 0.05), (c, 0.50), (d, 0.30), (e, 0.04), (f, 0.10)] > > and you want to drawn n items from that list (duplicates allowed), with > that probability distribution. > > The fastest algorithm that I have been able to devise for doing so is: > O(n * log(len(lst))). Can anyone think or a solution with a better time > complexity? If not, is there an obviously better way to do this > (assuming n is big and the list size is small). > > Here is the code: > > from random import random > from bisect import bisect > > def draw(n, lst): > ps = [] > last = 0 > for p in lst: > ps.append(last + p) > last += p > > # ps = [0.01, 0.06, 0.56, 0.86, 0.90, 1.00] > > chosen = [0] * len(lst) # track frequency > for i in range(n): > r = random() > > chosen[bisect(ps, r)] += 1 # binary search and increment > > result = [] # rescale probability based on frequency > for c in chosen: > result.append(float(c) / n) > return result > > lst = [0.01, 0.05, 0.50, 0.30, 0.04, 0.10] > print draw(10000, lst) > I would do something like the following (maybe with an additional check that the probabilities do not sum to less than 1), >>> from random import random >>> import operator >>> def draw(n, lst): lst.sort(key=operator.itemgetter(1), reverse=True) cumprobs = [] this_cp = 0 for p in lst: this_cp += p[1] cumprobs.append(this_cp) for _ in xrange(n): rnd = random() for i, cumprob in enumerate(cumprobs): if rnd < cumprob: yield lst[i][0] break >>> lst = [('a', 0.01), ('b', 0.05), ('c', 0.50), ('d', 0.30), ('e', 0.04), ('f', 0.10)] >>> list(draw(8, lst)) ['d', 'd', 'c', 'e', 'c', 'd', 'c', 'f'] >>> The sorting of the list means that iterating over the cumulative probabilities is minimised (for your density function the inner loop will be broken out of after the first iteration 50% of the time). (I've assumed that it doesn't matter to you that the list is sorted.) I'm not sure that this is in any way optimal. Duncan From alanalan at newsgroup.nospam Fri Jun 2 19:09:08 2006 From: alanalan at newsgroup.nospam (A.M) Date: Fri, 2 Jun 2006 13:09:08 -0400 Subject: Conditional Expressions in Python 2.4 References: <4480042b$0$29879$636a55ce@news.free.fr> Message-ID: >> a = 1 == 1 and "Yes" or "No" >> a = ("No", "Yes")[1 == 1] Smart! Thanks alot. From aahz at pythoncraft.com Fri Jun 2 19:29:29 2006 From: aahz at pythoncraft.com (Aahz) Date: 2 Jun 2006 10:29:29 -0700 Subject: Are there something like "Effective Python"? References: <1149224468.481470.74580@i39g2000cwa.googlegroups.com> Message-ID: In article <1149224468.481470.74580 at i39g2000cwa.googlegroups.com>, Mike Meng wrote: > > For example, one of my friends read my program and suggest me to >move the re.compile() out of a for-loop, since the regular pattern is >fixed, and re.compile() is slow. I want to find more such advice, where >can I find them? Actually, that's a good example of a false optimization, unless you're using a lot of different regexes in the loop or it's an extremely tight loop, because the re module already caches regexes. Still, if it's a constant string, a good programmer would probably hoist it out of the loop because you should hoist ALL constant assignments out of a loop. (It's not particularly related to re.compile() in this case.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I saw `cout' being shifted "Hello world" times to the left and stopped right there." --Steve Gonedes From tkpmep at hotmail.com Fri Jun 2 19:39:36 2006 From: tkpmep at hotmail.com (tkpmep at hotmail.com) Date: 2 Jun 2006 10:39:36 -0700 Subject: PyExcelerator Message-ID: <1149269975.981840.286750@j55g2000cwa.googlegroups.com> I write data to Excel files using PyExcelerator 0.6.3.a and have done so successfully for small files (10-15 cells). I'm experiencing an error when writing a big chunk of data (10,000 cells) to Excel. By way of comparison, the same data writes perfectly well to a csv file using Python's built in csv module. I run the program in PyScripter, and the traceback shows the following sequence of calls: main (my routine) writeData (my routine) save Line 563 get_biff_data Line 548 get_biff_data Line 1357 __row_blocks_rec Line 1276 get_cells_biff_data Line 200 get_biff_data Line 106 SystemError: frexp() result out of range The line it stops at in get_biff_data is the line that starts with packed = def get_biff_data(self): rk_encoded = 0 packed = struct.pack(' Message-ID: <1149270463.305631.22070@c74g2000cwc.googlegroups.com> >> for album in listdir(getcwd()): doesn't listdir give you subdirectories AND files? So, then if you try to: chdir(album) If album is a file, it chokes? Just a guess. I'm on Windows, not Linux. rd From donn at u.washington.edu Fri Jun 2 19:52:41 2006 From: donn at u.washington.edu (Donn Cave) Date: Fri, 02 Jun 2006 10:52:41 -0700 Subject: os.chdir doesn't accept variables sometimes References: <1149267516.348440.60290@u72g2000cwu.googlegroups.com> Message-ID: In article <1149267516.348440.60290 at u72g2000cwu.googlegroups.com>, "dannycolligan at gmail.com" wrote: > #!/usr/bin/python > > from os import * > > chdir("/home/chainlynx/Desktop/Music") > for artist in listdir(getcwd()): > print "===ARTIST: "+artist > chdir(artist) > for album in listdir(getcwd()): > print "---ALBUM: "+album > print "CWD: " + getcwd() > chdir(album) ######ERROR ON THIS > LINE > for string in listdir(album): ... > Traceback (most recent call last): > File "/home/chainlynx/workspace/PyTest/src/pypack/__init__.py", line > 12, in ? > for string in listdir(album): > OSError: [Errno 2] No such file or directory: 'Album1' To start with, note that your traceback implicates the listdir() on line 12, not the chdir() before it. This listdir() uses the same parameter as that preceding chdir(), that appears to be your problem. One of your problems, anyway. You're doing a lot of downwards chdirs, but no upwards, which is going to limit the extent of your directory traversal. The "from os import *" is a terrible idea, where did you get that? "os" has a lot of identifiers in it that tend to collide with other namespaces. "open" is a classic example. Don't do that, with "os" or generally any module. As a more general direction, it would be a good idea to look into standard library functions, e.g., os.path.walk > P.S. Bonus points: is there any way to bash shell script this on the > command line instead (recursively)? Depends on what you want it to do, but maybe something like find . -name \*.mp3 -exec $HOME/bin/cvt .mp4 {} \; where cvt would be something like #!/bin/sh case $1:$2 in .mp4:*.mp3) mp3_to_mp4 $2 ${2%.mp3}.mp4 ;; ... You'd have to think about it. Donn Cave, donn at u.washington.edu From gene.tani at gmail.com Fri Jun 2 19:55:36 2006 From: gene.tani at gmail.com (gene tani) Date: 2 Jun 2006 10:55:36 -0700 Subject: Are there something like "Effective Python"? In-Reply-To: <1149224468.481470.74580@i39g2000cwa.googlegroups.com> References: <1149224468.481470.74580@i39g2000cwa.googlegroups.com> Message-ID: <1149270936.264741.39820@y43g2000cwc.googlegroups.com> Mike Meng wrote: > Hi all, > I just finished reading Learning Python 3rd ed, and am doing my > first Python application, which retrieves and process text and XML > documents from Web. Python helped me to write the application in a few > hours, I'm very happy with its productivity. But the performance is not > satisfactory. I decide to optimized it in Python before trying C/C++ > extensions. But I don't know Python much and have no clu to tune my > program. Also, I don't know what Pythonist's preferred styles. Are > there any books/documents which play the similar role for Python as > 'Effective C++' does for C++? > > For example, one of my friends read my program and suggest me to > move the re.compile() out of a for-loop, since the regular pattern is > fixed, and re.compile() is slow. I want to find more such advice, where > can I find them? > Here's some links to profiling tools http://www.python.org/doc/current/lib/profile.html http://www.onlamp.com/lpt/a/6376 http://www.vrplumber.com/programming/runsnakerun/ http://mail.python.org/pipermail/python-list/2006-January/318295.html From writeson at charter.net Fri Jun 2 20:07:06 2006 From: writeson at charter.net (writeson) Date: 2 Jun 2006 11:07:06 -0700 Subject: wxPython problems with Fedora Core 5 Message-ID: <1149271626.481398.34440@h76g2000cwa.googlegroups.com> Hi all, I'm trying to use wxPython from a fairly new installation of Fedora Core 5. I installed wxPython using yum -y install wxPython and that all seemed to work fine. However, when I run Python and do this: import wx I get this: Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/site-packages/wx/__init__.py", line 45, in ? from wxPython import wx File "/usr/lib/python2.4/site-packages/wxPython/__init__.py", line 20, in ? import wxc ImportError: /usr/lib/libwx_gtk2-2.4.so.0: undefined symbol: pango_x_get_context Anyone have any ideas what's going on and what I can do to fix this? Thanks in advance, Doug From sjdevnull at yahoo.com Fri Jun 2 20:12:00 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 2 Jun 2006 11:12:00 -0700 Subject: How do you practice Python? In-Reply-To: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> References: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> Message-ID: <1149271920.917381.112910@u72g2000cwu.googlegroups.com> Ray wrote: > In our field, we don't always get to program in the language we'd like > to program. So... how do you practice Python in this case? Write code. Lots of it. Work on a project at home, contribute to something open source, use it to write support scripts at work, whatever. Figure out a way to write code. From overly.crazy.steve at gmail.com Fri Jun 2 20:12:38 2006 From: overly.crazy.steve at gmail.com (overly.crazy.steve at gmail.com) Date: 2 Jun 2006 11:12:38 -0700 Subject: execfile then import back In-Reply-To: References: <1149208230.216141.5400@f6g2000cwb.googlegroups.com> <1149208503.207296.204200@i39g2000cwa.googlegroups.com> Message-ID: <1149271958.509934.141110@j55g2000cwa.googlegroups.com> Dennis Lee Bieber wrote: > And the problem you are seeing is that the initial "v" in the t.py > that you "run", is considered "__main__.v", NOT "t.v" Yes, the 2 different copies of v apparently imply that __main__ and t are 2 different modules. But I had expected __main__ to be an alias of t. Can you point out the passage in Python doc that explains this? From sreeram at tachyontech.net Fri Jun 2 20:19:17 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Fri, 02 Jun 2006 23:49:17 +0530 Subject: announce: DaVinci Rendering Engine Message-ID: <44808125.9050607@tachyontech.net> Hi All, I've started working on a new open source graphics library called DaVinci. DaVinci aims to provide a declarative vector graphics based framework for building GUIs. http://tachyon.in/davinci/ It is being built on top of Anti-Grain Geometry and PyQt4. Currently, dvpaint, a python wrapper around AGG is available, along with some demo code. Any and all feedback is welcome! Regards Sreeram -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 252 bytes Desc: OpenPGP digital signature Url : http://mail.python.org/pipermail/python-list/attachments/20060602/2d7f0ae6/attachment.pgp From steven.bethard at gmail.com Fri Jun 2 20:21:08 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 02 Jun 2006 12:21:08 -0600 Subject: Conditional Expressions in Python 2.4 In-Reply-To: <4480042b$0$29879$636a55ce@news.free.fr> References: <4480042b$0$29879$636a55ce@news.free.fr> Message-ID: <7OidneazQ9UJHB3ZnZ2dnUVZ_sGdnZ2d@comcast.com> A.M wrote: > Do we have the conditional expressions in Python 2.4? bruno at modulix wrote: > No, AFAIK they'll be in for 2.5 Yep: Python 2.5a2 (trunk:46491M, May 27 2006, 14:43:55) [MSC v.1310 32 bit (Intel)] on win32 >>> "Yes" if 1 == 1 else "No" 'Yes' > In the meanwhile, there are (sometime tricky? ways to get the same result: > > a = 1 == 1 and "Yes" or "No" > a = ("No", "Yes")[1 == 1] And just to give some examples where the conditional expression will show a difference:: >>> True and 0 or [] [] >>> 0 if True else [] 0 >>> def f(): ... print "don't evaluate me" ... return 'f' ... >>> def g(): ... return 'g' ... >>> (f(), g())[True] don't evaluate me 'g' >>> g() if True else f() 'g' STeVe From tjreedy at udel.edu Fri Jun 2 20:33:44 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 2 Jun 2006 14:33:44 -0400 Subject: An oddity in list comparison and element assignment References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com><1149194434.528648.148860@u72g2000cwu.googlegroups.com><1hg9onn.p25evr18a09f9N%aleax@mac.com> Message-ID: "Aahz" wrote in message news:e5pr7u$3g0$1 at panix3.panix.com... > Except, of course, that BofA doesn't exist anymore. Oh, the *name* > does, but what's now called BofA is simply the current name of the bank > that acquired BofA. In Pythonese, they performed SomeBank.extend(BofA) BofA = SomeBank del SomeBank so that id(BofA) is now what id(SomeBank) was, not what was id(the BofA I grew up with). The name was definitely part of of the acquisition value. ;-) OT, but not completely irrelevant to a discussion of names, ids, and values. Terry Jan Reedy From xivulon at gmail.com Fri Jun 2 20:40:28 2006 From: xivulon at gmail.com (ago) Date: 2 Jun 2006 11:40:28 -0700 Subject: win32com: how to connect to a specific instance of a running object? In-Reply-To: <1149260253.337452.65770@c74g2000cwc.googlegroups.com> References: <1149254270.790703.145700@j55g2000cwa.googlegroups.com> <1149260253.337452.65770@c74g2000cwc.googlegroups.com> Message-ID: <1149273628.486179.224680@h76g2000cwa.googlegroups.com> solved, if it can be useful to others here is my code: import pythoncom import win32com.client def getWorkbook(workbookName): lenstr = len(workbookName) workbook = None rot = pythoncom.GetRunningObjectTable() rotenum = rot.EnumRunning() while True: monikers = rotenum.Next() if not monikers: break ctx = pythoncom.CreateBindCtx(0) name = monikers[0].GetDisplayName(ctx, None); if name[-lenstr:] == workbookName: obj = rot.GetObject(monikers[0]) workbook = win32com.client.Dispatch(obj.QueryInterface(pythoncom.IID_IDispatch)) return workbook From nun at example.com Fri Jun 2 20:58:29 2006 From: nun at example.com (Mitja Trampus) Date: Fri, 02 Jun 2006 20:58:29 +0200 Subject: Sampling a population In-Reply-To: References: Message-ID: Brian Quinlan wrote: > The fastest algorithm that I have been able to devise for doing so is: > O(n * log(len(lst))). Can anyone think or a solution with a better time > complexity? If not, is there an obviously better way to do this > (assuming n is big and the list size is small). If list is indeed short, I'd say common sense speaks against complicating and optimizing further - you can only get log(len(lst))-fold speedup, which is in your case more or less a small constant. _IF_ this part of code later turns out to be a bottleneck, you might profit more by porting it to C than searching for an O(n) solution, if it even exists. From hancock at anansispaceworks.com Fri Jun 2 21:11:11 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 02 Jun 2006 19:11:11 +0000 Subject: An oddity in list comparison and element assignment In-Reply-To: <1hg9onn.p25evr18a09f9N%aleax@mac.com> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> <447f152f@nntp0.pdx.net> <1149194434.528648.148860@u72g2000cwu.googlegroups.com> <1hg9onn.p25evr18a09f9N%aleax@mac.com> Message-ID: <44808D4F.9070001@anansispaceworks.com> Alex Martelli wrote: > Slawomir Nowaczyk wrote: > > On Thu, 01 Jun 2006 13:40:34 -0700 michael.f.ellis at gmail.com wrote: > > #> Scott David Daniels wrote: #> > Would you say that envelope > > containing five $100 bills is equal to #> > an envelope containing > > five $100 bills with different serial numbers? > > > > #> Yes (unless I was testing the assertion that the second envelope > > did #> not contain counterfeits of the first) > > > > So, what if Bank of America later decided that bills with serial > > numbers containing "7" are no longer valid? > > Then Wachowia would no doubt be happy to take my business away from > BoA;-). > > I suspect you believe BoA is some kind of "official" body -- it > isn't, just like Deutschebank is not one in Germany (rather, > Bundesbank is). Yeah, it's a funny mistake, but what he meant, is what if the US Treasury Department declared bills with serial numbers containing "7" invalid. That would indeed complete the analogy. And it's a sharp example -- because money is conceived of as fungible, one $100 is as good as another, so two $100 bills compare as equal, whether they are equal or not. Of course, the counter argument is that it's not unlike counting a reflection of a $100 bill as another $100 and concluding that you have $200 (you need two mirrors to double your money, technically ;-)). I don't think there's any way to make it "more logical" -- it's going to break somewhere no matter what assumption you make, so you just have to learn what's really going on in order to avoid confusion. Cheers, Terry -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From paddy3118 at netscape.net Fri Jun 2 21:09:54 2006 From: paddy3118 at netscape.net (Paddy) Date: 2 Jun 2006 12:09:54 -0700 Subject: Sampling a population References: Message-ID: <1149275394.499808.31460@i39g2000cwa.googlegroups.com> Brian Quinlan wrote: > This is less a Python question and more a optimization/probability > question. Imaging that you have a list of objects and there frequency in > a population e.g. > > lst = [(a, 0.01), (b, 0.05), (c, 0.50), (d, 0.30), (e, 0.04), (f, 0.10)] > > and you want to drawn n items from that list (duplicates allowed), with > that probability distribution. > > The fastest algorithm that I have been able to devise for doing so is: > O(n * log(len(lst))). Can anyone think or a solution with a better time > complexity? If not, is there an obviously better way to do this > (assuming n is big and the list size is small). > Any way I tried to slice and dice it, I could not get any faster. draw2 and draw 3 generate code on the fly. draw4 sneakily tries to trade memory and accuracy for speed but is even slower! First the times, then the code: $ ./timeit.py 'from probDistribution import draw as draw; draw(10000, [0.01, 0.05, 0.50, 0.30, 0.04, 0.10])' 100 loops, best of 3: 13.4 msec per loop $ ./timeit.py 'from probDistribution import draw2 as draw; draw(10000, [0.01, 0.05, 0.50, 0.30, 0.04, 0.10])' 100 loops, best of 3: 15.2 msec per loop $ ./timeit.py 'from probDistribution import draw3 as draw; draw(10000, [0.01, 0.05, 0.50, 0.30, 0.04, 0.10])' 100 loops, best of 3: 16.2 msec per loop $ ./timeit.py 'from probDistribution import draw4 as draw; draw(10000, [0.01, 0.05, 0.50, 0.30, 0.04, 0.10])' 10 loops, best of 3: 30.5 msec per loop === CODE probDistribution.py === from random import random, randrange from bisect import bisect def draw(n, lst): ps = [] last = 0 for p in lst: ps.append(last + p) last += p # ps = [0.01, 0.06, 0.56, 0.86, 0.90, 1.00] chosen = [0] * len(lst) # track frequency for i in range(n): r = random() chosen[bisect(ps, r)] += 1 # binary search and increment result = [] # rescale probability based on frequency for c in chosen: result.append(float(c) / n) return result def draw2(n, lst): """ uses dynamicc code generation of this form: chosen = [0] * 6 for i in xrange(10000): r = random() if r < 0.01: chosen[0]+=1 elif r < 0.06: chosen[1] +=1 ... elif r < 0.90: chosen[4] +=1 else chosen[5]+=1 """ assert len(lst)>1, "Corner case NOT covered" codestr = 'chosen = [0] * %i\n' % (len(lst),) codestr += 'for i in xrange(%i):\n r = random()\n' % (n,) last = 0.0 lstmax = len(lst)-1 for i,p in enumerate(lst): last += p if i==0: codestr += ' if r < %g: chosen[%i] +=1\n' % (last, i) elif i==lstmax: codestr += ' else: chosen[%i] +=1\n' % (i,) else: codestr += ' elif r < %g: chosen[%i] +=1\n' % (last, i) exec codestr result = [] # rescale probability based on frequency for c in chosen: result.append(float(c) / n) return result def draw3(n, lst): """ uses dynamicc code generation of this form: chosen = [0] * 6 for i in xrange(10000): r = random() chosen[-1+ ( ((r<0.01) and 1) or ((r<0.06) and 2) ... or ((r<0.90) and 5) or 6 )] +=1 """ assert len(lst)>1, "Corner case NOT covered" codestr = 'chosen = [0] * %i\n' % (len(lst),) codestr += 'for i in xrange(%i):\n r = random()\n' % (n,) codestr += ' chosen[-1+ (\n' last = 0.0 lstmax = len(lst)-1 for i,p in enumerate(lst): last += p if i==0: codestr += ' ((r<%g) and 1)\n' % (last) elif i==lstmax: codestr +=