From wescpy at gmail.com Sat Jun 24 02:23:00 2006 From: wescpy at gmail.com (w chun) Date: Fri, 23 Jun 2006 17:23:00 -0700 Subject: Error with OpenOffice Message-ID: <78b3a9580606231723i5a994737s595eb8c58d6d0b1a@mail.gmail.com> > Subject: Error with OpenOffice > From: "Mario Lacunza" > Date: Thu Apr 20 06:30:19 CEST 2006 > > I try to make the exercises found in Ooo website but I receipt this > error: > > mario at laptop:~$ python > Python 2.4.2 (#2, Sep 30 2005, 21:19:01) > [GCC 4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu8)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import uno > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.4/site-packages/uno.py", line 37, in ? > import pyuno > SystemError: dynamic module not initialized properly > > Any idea?? > > Mi configuracion/My config: > > Ubuntu Breezy 5.10 > Linux Kernel 2.6.12-10-386 > Python 2.4.2 > wxPython 2.6.1.1Pre > OpenOffice 2.0.1 hola mario, of the software you listed above, did you manually compile any? i am using the exact same release as you: Ubuntu Breezy 5.10 Linux Kernel 2.6.12-10-386 Python 2.4.2 the only difference is that i'm using OpenOffice2 version 1.9.129. i have not loaded wxPython yet, but all of the software listed was installed as Ubuntu packages (not hand-built). i am able to do this: $ python Python 2.4.2 (#2, Sep 30 2005, 21:19:01) [GCC 4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu8)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import uno >>> import sys >>> >>> sys.modules['uno'] >>> >>> sys.modules['pyuno'] -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From kenneth.m.mcdonald at sbcglobal.net Wed Jun 28 22:52:27 2006 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Wed, 28 Jun 2006 15:52:27 -0500 Subject: [OT] Prolog and Regular Expressions, Was: Re: perspective on ruby In-Reply-To: References: <1145555339.316764.123210@i39g2000cwa.googlegroups.com> <1he41sz.r7aasv1oo5lfN%aleaxit@yahoo.com> Message-ID: <44A2EC0B.10000@sbcglobal.net> Lawrence D'Oliveiro wrote: > In article , > Edward Elliott wrote: > > >> XML? Conceptually (and more elegantly) covered >> as LISP s-expressions. >> > > "...Lisp is still #1 for key algorithmic techniques such as recursion > and condescension." > -- Verity Stob > > > >> XSLT? Just a bastardized spawn of Prolog. >> > > As is any kind of pattern matching, including everyone's favourite > regular expressions. Prolog did it all. > I'm assuming you're kidding--there is a lot of difference between an RE that produces a highly optimized finite state machine to quickly match a string, and a language that uses brute-force depth-first recursion, plus some nonobvious tricks, to do the same thing. Like many orders of magnitude in execution time :-) That said, it'd be nice if there were some easy way to access a Prolog engine from Python. When Prolog is appropriate, it's _really_ appropriate. Cheers, Ken From harry.g.george at boeing.com Thu Jun 29 07:27:46 2006 From: harry.g.george at boeing.com (Harry George) Date: Thu, 29 Jun 2006 05:27:46 GMT Subject: [OT] Prolog and Regular Expressions, Was: Re: perspective on ruby References: <1145555339.316764.123210@i39g2000cwa.googlegroups.com> <1he41sz.r7aasv1oo5lfN%aleaxit@yahoo.com> Message-ID: Kenneth McDonald writes: [snip] > > That said, it'd be nice if there were some easy way to access a Prolog > engine from Python. When Prolog is appropriate, it's _really_ > appropriate. > > > Cheers, > Ken > http://christophe.delord.free.fr/en/pylog/ http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303057 http://www.ibiblio.org/obp/py4fun/prolog/prolog2.html http://sourceforge.net/projects/pyprolog/ Also, before these showed up, we locally did prolog-calls-python and python-calls-prolog (all from a C++ CAD engine) by using the embedding libraries and bindings. -- Harry George PLM Engineering Architecture From wescpy at gmail.com Sat Jun 24 02:36:17 2006 From: wescpy at gmail.com (w chun) Date: Fri, 23 Jun 2006 17:36:17 -0700 Subject: OpenOffice UNO export PDF help needed Message-ID: <78b3a9580606231736q638e637l42f733e40721df3c@mail.gmail.com> > > Subject: OpenOffice UNO export PDF help needed > > From: "Sells, Fred" > > Date: Sun Apr 30 04:17:43 CEST 2006 > > > > I've geen googling for 3 days now, and cannot find out how to do this. > > > > I'm trying to use OpenOffice 2.0 and UNO to generate PDF documents. I'm > > using windows, but will have to make it work under Linux for production. > > I've been able to set the parameters and call the exportToPdf method, but > > the exported file is not PDF but an .odt document, > > : > > below is a java code snippet, submitted with apologies, I'm using that > > rather than python because I found better examples and my java IDE helps me > > out. I originally started out to do python, and will eventually shift back > > to it once I get this working > > > Subject: OpenOffice UNO export PDF help needed > From: "Michele Petrazzo" > Date: Mon May 1 11:37:07 CEST 2006 > > Have you tried the ooextract.py found on: > http://udk.openoffice.org/python/python-bridge.html > > Here work well and generate a pdf file. > > See also this for more info about generate pdf: > http://mithrandr.moria.org/blog/447.html fred, have you had any luck with either your Java or Python code? did you take a look at the code that Michele had suggested? please post your progress or any errors you encounter as others on the list are interested too. what version of OOo are you using? thanks, -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wescpy at gmail.com Sat Jun 24 02:43:15 2006 From: wescpy at gmail.com (w chun) Date: Fri, 23 Jun 2006 17:43:15 -0700 Subject: pyuno and oootools with OpenOffice 2.0 Message-ID: <78b3a9580606231743p29f64189o72fddc420719c5fe@mail.gmail.com> > Subject: pyuno and oootools with OpenOffice 2.0 > From: "Sells, Fred" > Date: Thu May 4 17:37:35 CEST 2006 > > I'm using windows xp and OpenOffice 2.0 and doing my first project with > pyuno. > > I've got the basics to work,. An example I googled at > http://blogs.nuxeo.com/sections/aggregators/openoffice_org/blogaggregator_view?b_start:int=0 > imported an ootools module. When I try to import it, it does not exist, > > Does anyone know where this exists, or why I cannot import it. the oootools.py module is referenced in this blog entry: http://blogs.nuxeo.com/sections/blogs/laurent_godard/2006_04_13_testing-pyuno-programs-with-doctests the direct link to download this file is: http://blogs.nuxeo.com/sections/blogs/laurent_godard/2006_04_13_testing-pyuno-programs-with-doctests/downloadFile/attachedFile_1_f0/oootools.py HTH, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wescpy at gmail.com Sat Jun 24 02:54:26 2006 From: wescpy at gmail.com (w chun) Date: Fri, 23 Jun 2006 17:54:26 -0700 Subject: pyuno and PDF output Message-ID: <78b3a9580606231754i7921e733l8625c14002cf6615@mail.gmail.com> > Subject: pyuno and PDF output > From: "Sells, Fred" > Date: Thu May 4 19:20:57 CEST 2006 > > I can use java to output a PDF file using uno, but when I try to do it in > python, I get an IO Exception with no added information. The relevant code > snippet follows: > > from com.sun.star.beans import PropertyValue > PDF = PropertyValue( "FilterName" , 0 , "writer_pdf_Export", 0 ) > doc2.storeAsURL("file:///C:/alleclipse/OpenOffice/test2.pdf", (PDF,) ) > > if I don't specify any properties, it writes an "odt" file just fine, but > when I specify (PDF,) it breaks. > > Traceback (most recent call last): > File "oomerge.py", line 137, in ? > test1() > File "oomerge.py", line 74, in test1 > doc2.storeAsURL("file:///C:/alleclipse/OpenOffice/test2.pdf", (PDF,) ) > __main__.com.sun.star.task.ErrorCodeIOException fred, (man, i hate seeing that error too... it gets old *fast*.) a couple of suggestions here: 1. use unohelper with filenames (see #3 below) import unohelper 2. use the short form to instantiate a PropertyValue REPLACE: PDF = PropertyValue("FilterName", 0, "writer_pdf_Export", 0) WITH: PDF = PropertyValue("FilterName", "writer_pdf_Export") 3. use storeToURL() as opposed to storeAsURL() REPLACE: doc2.storeAsURL("file:///C:/alleclipse/OpenOffice/test2.pdf", (PDF,)) WITH: doc2.storeToURL(unohelper.absolutize( unohelper.systemPathToFileUrl('C:/alleclipse/OpenOffice/test2.pdf'), unohelper.systemPathToFileUrl('test2.pdf')), (PDF,)) let us know how/if/whether this works. HTH, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From cbaoqiu at yahoo.com Sun Jun 4 18:51:03 2006 From: cbaoqiu at yahoo.com (Baoqiu Cui) Date: Sun, 04 Jun 2006 16:51:03 GMT Subject: deleting texts between patterns References: <1147420279.664699.181200@i40g2000cwc.googlegroups.com> <1147421468.912908.271280@i39g2000cwa.googlegroups.com> <44645C03.3070500@lexicon.net> Message-ID: John Machin writes: > Uh-oh. > > Try this: > >>>> pat = re.compile('(?<=abc\n).*?(?=xyz\n)', re.DOTALL) >>>> re.sub(pat, '', linestr) > 'blahfubarabc\nxyz\nxyzzy' This regexp still has a problem. It may remove the lines between two lines like 'aaabc' and 'xxxyz' (and also removes the first two 'x's in 'xxxyz'). The following regexp works better: pattern = re.compile('(?<=^abc\n).*?(?=^xyz\n)', re.DOTALL | re.MULTILINE) >>> lines = '''line1 ... abc ... line2 ... xyz ... line3 ... aaabc ... line4 ... xxxyz ... line5''' >>> pattern = re.compile('(?<=^abc\n).*?(?=^xyz\n)', re.DOTALL | re.MULTILINE) >>> print pattern.sub('', lines) line1 abc xyz line3 aaabc line4 xxxyz line5 >>> - Baoqiu -- Baoqiu Cui From sjmachin at lexicon.net Mon Jun 5 01:36:14 2006 From: sjmachin at lexicon.net (John Machin) Date: Mon, 05 Jun 2006 09:36:14 +1000 Subject: deleting texts between patterns In-Reply-To: References: <1147420279.664699.181200@i40g2000cwc.googlegroups.com> <1147421468.912908.271280@i39g2000cwa.googlegroups.com> <44645C03.3070500@lexicon.net> Message-ID: <44836E6E.3070709@lexicon.net> On 5/06/2006 2:51 AM, Baoqiu Cui wrote: > John Machin writes: > >> Uh-oh. >> >> Try this: >> >>>>> pat = re.compile('(?<=abc\n).*?(?=xyz\n)', re.DOTALL) >>>>> re.sub(pat, '', linestr) >> 'blahfubarabc\nxyz\nxyzzy' > > This regexp still has a problem. It may remove the lines between two > lines like 'aaabc' and 'xxxyz' (and also removes the first two 'x's in > 'xxxyz'). > > The following regexp works better: > > pattern = re.compile('(?<=^abc\n).*?(?=^xyz\n)', re.DOTALL | re.MULTILINE) > You are quite correct. Your reply, and the rejoinder below, only add to the proposition that regexes are not necessarily the best choice for every text-processing job :-) Just in case the last line is 'xyz' but is not terminated by '\n': pattern = re.compile('(?<=^abc\n).*?(?=^xyz$)', re.DOTALL | re.MULTILINE) Cheers, John From ldo at geek-central.gen.new_zealand Mon Jun 5 11:27:57 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 05 Jun 2006 21:27:57 +1200 Subject: Large Dictionaries References: <1147699064.107490@teuthos> <1147772420.405097@teuthos> <1147818548.532882.94180@i39g2000cwa.googlegroups.com> <1147874585.728471@teuthos> <1148514158.790760.205630@i40g2000cwc.googlegroups.com> <447af556$1@nntp0.pdx.net> Message-ID: In article <447af556$1 at nntp0.pdx.net>, Scott David Daniels wrote: >For example, time timsort (Python's internal sort) on pre-sorted >data; you'll find it is handled faster than random data. But isn't that how a reasonable sorting algorithm should behave? Less work to do if the data is already sorted? From steve at holdenweb.com Mon Jun 5 13:25:28 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 05 Jun 2006 12:25:28 +0100 Subject: Large Dictionaries In-Reply-To: References: <1147699064.107490@teuthos> <1147772420.405097@teuthos> <1147818548.532882.94180@i39g2000cwa.googlegroups.com> <1147874585.728471@teuthos> <1148514158.790760.205630@i40g2000cwc.googlegroups.com> <447af556$1@nntp0.pdx.net> Message-ID: Lawrence D'Oliveiro wrote: > In article <447af556$1 at nntp0.pdx.net>, > Scott David Daniels wrote: > > >>For example, time timsort (Python's internal sort) on pre-sorted >>data; you'll find it is handled faster than random data. > > > But isn't that how a reasonable sorting algorithm should behave? Less > work to do if the data is already sorted? Isn't that just your definition of "reasonable"? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From aahz at pythoncraft.com Mon Jun 5 16:06:30 2006 From: aahz at pythoncraft.com (Aahz) Date: 5 Jun 2006 07:06:30 -0700 Subject: Large Dictionaries References: <1147699064.107490@teuthos> <447af556$1@nntp0.pdx.net> Message-ID: In article , Lawrence D'Oliveiro wrote: >In article <447af556$1 at nntp0.pdx.net>, > Scott David Daniels wrote: >> >>For example, time timsort (Python's internal sort) on pre-sorted >>data; you'll find it is handled faster than random data. > >But isn't that how a reasonable sorting algorithm should behave? Less >work to do if the data is already sorted? Read some of the old discussions in the python-dev archives. -- 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 iainking at gmail.com Mon Jun 5 16:28:40 2006 From: iainking at gmail.com (Iain King) Date: 5 Jun 2006 07:28:40 -0700 Subject: Large Dictionaries In-Reply-To: References: <1147699064.107490@teuthos> <1147772420.405097@teuthos> <1147818548.532882.94180@i39g2000cwa.googlegroups.com> <1147874585.728471@teuthos> <1148514158.790760.205630@i40g2000cwc.googlegroups.com> <447af556$1@nntp0.pdx.net> Message-ID: <1149517720.086866.3510@j55g2000cwa.googlegroups.com> Lawrence D'Oliveiro wrote: > In article <447af556$1 at nntp0.pdx.net>, > Scott David Daniels wrote: > > >For example, time timsort (Python's internal sort) on pre-sorted > >data; you'll find it is handled faster than random data. > > But isn't that how a reasonable sorting algorithm should behave? Less > work to do if the data is already sorted? An already sorted list can be pathological for Quicksort, depending on how you code it. Iain From ldo at geek-central.gen.new_zealand Thu Jun 8 23:55:05 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 09 Jun 2006 09:55:05 +1200 Subject: Large Dictionaries References: <1147699064.107490@teuthos> <1147772420.405097@teuthos> <1147818548.532882.94180@i39g2000cwa.googlegroups.com> <1147874585.728471@teuthos> <1148514158.790760.205630@i40g2000cwc.googlegroups.com> <447af556$1@nntp0.pdx.net> <1149517720.086866.3510@j55g2000cwa.googlegroups.com> Message-ID: In article <1149517720.086866.3510 at j55g2000cwa.googlegroups.com>, "Iain King" wrote: >Lawrence D'Oliveiro wrote: >> In article <447af556$1 at nntp0.pdx.net>, >> Scott David Daniels wrote: >> >> >For example, time timsort (Python's internal sort) on pre-sorted >> >data; you'll find it is handled faster than random data. >> >> But isn't that how a reasonable sorting algorithm should behave? Less >> work to do if the data is already sorted? > >An already sorted list can be pathological for Quicksort, depending on >how you code it. I did say "reasonable". :) From tim.peters at gmail.com Mon Jun 5 16:52:22 2006 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 5 Jun 2006 10:52:22 -0400 Subject: Large Dictionaries In-Reply-To: References: <1147699064.107490@teuthos> <1147772420.405097@teuthos> <1147818548.532882.94180@i39g2000cwa.googlegroups.com> <1147874585.728471@teuthos> <1148514158.790760.205630@i40g2000cwc.googlegroups.com> <447af556$1@nntp0.pdx.net> Message-ID: <1f7befae0606050752t7d2b0403m872aed970da30401@mail.gmail.com> [Scott David Daniels] >> For example, time timsort (Python's internal sort) on pre-sorted >> data; you'll find it is handled faster than random data. O(N) vs O(N log N), in fact. [Lawrence D'Oliveiro] > But isn't that how a reasonable sorting algorithm should behave? Less > work to do if the data is already sorted? For example, the O(N log N) heapsort is unreasonable compared to the O(N**2) bubblesort by that reasoning (pre-sorted is actually a bad case for heapsort, but a good case for bubblesort)? O(N log N) sorting algorithms helped by pre-existing order are uncommon, unless they do extra work to detect and exploit pre-existing order. Python's current sorting algorithm exploits pre-existing order of many kinds. For example, take a sorted list, "cut it in half, and riffle shuffle the two halves together"; e.g., [0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15] That turns out to be a supernaturally good case too. From jes at nl.demon.net Mon Jun 5 19:52:02 2006 From: jes at nl.demon.net (Jim Segrave) Date: Mon, 05 Jun 2006 17:52:02 -0000 Subject: Large Dictionaries References: <1147699064.107490@teuthos> <447af556$1@nntp0.pdx.net> Message-ID: <1288rq2mkj9r40b@corp.supernews.com> In article , Tim Peters wrote: >[Scott David Daniels] >>> For example, time timsort (Python's internal sort) on pre-sorted >>> data; you'll find it is handled faster than random data. > >O(N) vs O(N log N), in fact. > >[Lawrence D'Oliveiro] >> But isn't that how a reasonable sorting algorithm should behave? Less >> work to do if the data is already sorted? > >For example, the O(N log N) heapsort is unreasonable compared to the >O(N**2) bubblesort by that reasoning (pre-sorted is actually a bad >case for heapsort, but a good case for bubblesort)? O(N log N) >sorting algorithms helped by pre-existing order are uncommon, unless >they do extra work to detect and exploit pre-existing order. Actually, presorted lists are not a bad case for heapsort - it's quite immune to any existing order or lack thereof, whereas some other sorts, quicksort being a prime example, require great care to avoid pathological cases. -- Jim Segrave (jes at jes-2.demon.nl) From tim.peters at gmail.com Mon Jun 5 20:24:41 2006 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 5 Jun 2006 14:24:41 -0400 Subject: Large Dictionaries In-Reply-To: <1288rq2mkj9r40b@corp.supernews.com> References: <1147699064.107490@teuthos> <447af556$1@nntp0.pdx.net> <1288rq2mkj9r40b@corp.supernews.com> Message-ID: <1f7befae0606051124m1cde1096m1e021c53124437d5@mail.gmail.com> [Jim Segrave] > Actually, presorted lists are not a bad case for heapsort - it's quite > immune to any existing order or lack thereof, Write a heapsort and time it. It's not a difference in O() behavior, but more memory movement is required for a sorted list because transforming the list into a max-heap at the start requires shuffling the largest elements from the end of the list to its start. Initially reverse-sorted is a "good case" for heapsort in the same sense (because the list is already a max-heap then; initially sorted is as far from being a max-heap as is possible). "good" and "bad" are both O(N log N) here, though. BTW, most people have never heard of Smoothsort, which was Dijkstra's excruciating attempt to make heapsort exploit pre-existing order: http://www.cs.utexas.edu/users/EWD/ewd07xx/EWD796.PDF That's one of a hundred algorithms I rejected for Python ;-) > whereas some other sorts, quicksort being a prime example, require > great care to avoid pathological cases. Indeed, Python gave up on quicksort for that reason. While the samplesort hybrid that came between quicksort and the current sort also had theoretical O(N**2) worst-case behavior, it was exceedingly difficult to create such an input, and (unlike as for every quicksort variant Python tried) no real-life case of undue sloth was ever reported against it. From jes at nl.demon.net Mon Jun 5 22:15:27 2006 From: jes at nl.demon.net (Jim Segrave) Date: Mon, 05 Jun 2006 20:15:27 -0000 Subject: Large Dictionaries References: <1147699064.107490@teuthos> <1288rq2mkj9r40b@corp.supernews.com> Message-ID: <128946vm56t7627@corp.supernews.com> In article , Tim Peters wrote: >[Jim Segrave] >> Actually, presorted lists are not a bad case for heapsort - it's quite >> immune to any existing order or lack thereof, > >Write a heapsort and time it. It's not a difference in O() behavior, >but more memory movement is required for a sorted list because >transforming the list into a max-heap at the start requires shuffling >the largest elements from the end of the list to its start. Initially >reverse-sorted is a "good case" for heapsort in the same sense >(because the list is already a max-heap then; initially sorted is as >far from being a max-heap as is possible). "good" and "bad" are both >O(N log N) here, though. I did implement a crude heapsort before posting this and measured the number of comparisions and the number of swaps. ================================================== #!/usr/local/bin/python import random class HeapSorter(object): def __init__(self, seq): self.compares = 0 self.swaps = 0 self.length = len(seq) self.seq = seq def __sift(self, i): while True: j = 2 * i + 1 if j + 1 < self.length: self.compares += 1 if self.seq[j + 1] > self.seq[j]: j = j + 1 if j >= self.length: return self.compares += 1 if self.seq[i] > self.seq[j]: return self.swaps += 1 self.seq[i], self.seq[j] = (self.seq[j], self.seq[i]) i = j def __makeheap(self): for i in range(self.length / 2, -1, -1): self.__sift(i) def sort(self): self.__makeheap() for i in range(self.length - 1, -1, -1): self.swaps += 1 self.seq[i], self.seq[0] = (self.seq[0], self.seq[i]) self.length -= 1 self.__sift(0) if __name__ == '__main__': s = list(range(100000)) random.shuffle(s) heap = HeapSorter(s) heap.sort() print "Random list: comapres %d, swaps %d" % \ (heap.compares, heap.swaps) heap = HeapSorter(s) heap.sort() print "Sorted list: comapres %d, swaps %d" % \ (heap.compares, heap.swaps) s.reverse() heap = HeapSorter(s) heap.sort() print "Reverse Sorted list: comapres %d, swaps %d" % \ (heap.compares, heap.swaps) ================================================== Which gave the following results: /usr/home/jes% python ./heapsort Random list: comapres 3019969, swaps 1575263 Sorted list: comapres 3112517, swaps 1650855 Reverse Sorted list: comapres 2926640, swaps 1497435 Assuming compares and swaps dominate other bookkeeping, then heapsort is quite stable in its performance, although the constant in the O(N log N) is much larger than for other sorts. -- Jim Segrave (jes at jes-2.demon.nl) From ldo at geek-central.gen.new_zealand Thu Jun 8 23:54:47 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 09 Jun 2006 09:54:47 +1200 Subject: Large Dictionaries References: <1147699064.107490@teuthos> <1147772420.405097@teuthos> <1147818548.532882.94180@i39g2000cwa.googlegroups.com> <1147874585.728471@teuthos> <1148514158.790760.205630@i40g2000cwc.googlegroups.com> <447af556$1@nntp0.pdx.net> Message-ID: In article , "Tim Peters" wrote: >For example, the O(N log N) heapsort is unreasonable compared to the >O(N**2) bubblesort by that reasoning (pre-sorted is actually a bad >case for heapsort, but a good case for bubblesort)? O(N log N) >sorting algorithms helped by pre-existing order are uncommon, unless >they do extra work to detect and exploit pre-existing order. Shellsort works well with nearly-sorted data. It's basically a smarter version of bubblesort with much improved efficiency. It's also very compact to implement. From tim.peters at gmail.com Fri Jun 9 00:10:32 2006 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 8 Jun 2006 18:10:32 -0400 Subject: Large Dictionaries In-Reply-To: References: <1147699064.107490@teuthos> <1147772420.405097@teuthos> <1147818548.532882.94180@i39g2000cwa.googlegroups.com> <1147874585.728471@teuthos> <1148514158.790760.205630@i40g2000cwc.googlegroups.com> <447af556$1@nntp0.pdx.net> Message-ID: <1f7befae0606081510q5e9b6775r9e7d817c921f4ae4@mail.gmail.com> [Tim Peters] >> ... >> O(N log N) sorting algorithms helped by pre-existing order are >> uncommon, unless they do extra work to detect and exploit >> pre-existing order. [Lawrence D'Oliveiro] > Shellsort works well with nearly-sorted data. It's basically a smarter > version of bubblesort with much improved efficiency. It's also very > compact to implement. shellsort is much more a refinement of insertion-sort than of bubblesort, but is not an O(N log N) algorithm regardlesss. A nice, succinct summary of what was known about shellsort's behavior as of Sedgewick's 1996 "Analysis of Shellsort and Related Algorithms" can be found here: http://www.inf.fh-flensburg.de/lang/algorithmen/sortieren/shell/shellen.htm From Marcin.Ciura at NOSPAM.poczta.onet.pl Fri Jun 9 12:16:03 2006 From: Marcin.Ciura at NOSPAM.poczta.onet.pl (Marcin Ciura) Date: Fri, 09 Jun 2006 12:16:03 +0200 Subject: Large Dictionaries In-Reply-To: References: <1147699064.107490@teuthos> <1147772420.405097@teuthos> <1147818548.532882.94180@i39g2000cwa.googlegroups.com> <1147874585.728471@teuthos> <1148514158.790760.205630@i40g2000cwc.googlegroups.com> <447af556$1@nntp0.pdx.net> Message-ID: Tim Peters wrote: > shellsort is much more a refinement of insertion-sort than of > bubblesort, but is not an O(N log N) algorithm regardlesss. With a judiciously chosen increment sequence, the number of comparisons made by shellsort *is* of the order N log N for practical values of N. See Figure 8 in http://sun.iinf.polsl.gliwice.pl/~mciura/shellsort.pdf Marcin From duncan.booth at invalid.invalid Fri Jun 9 13:35:48 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Jun 2006 11:35:48 GMT Subject: Large Dictionaries References: <1147699064.107490@teuthos> Message-ID: Marcin Ciura wrote: > Tim Peters wrote: >> shellsort is much more a refinement of insertion-sort than of >> bubblesort, but is not an O(N log N) algorithm regardlesss. > > With a judiciously chosen increment sequence, > the number of comparisons made by shellsort > *is* of the order N log N for practical values of N. > See Figure 8 in > http://sun.iinf.polsl.gliwice.pl/~mciura/shellsort.pdf That isn't what the reference says. It only covers N up to a few thousand. Practical values of N need to at least go up into the millions. Read the summary: > Using sequential analysis, the search for optimal increment sequences > for Shellsort was accelerated enough to find them for arrays up to > several thousand elements. ... > However, the sequences obtained so far are too short to draw a > reliable conclusion whether an appropriate sequence of increments can > make Shellsort a O(N logN) sorting method on the average. Some > hypotheses may be possible when the sequences are prolonged to sort > arrays of about 10^5 elements. From Marcin.Ciura at NOSPAM.poczta.onet.pl Fri Jun 9 14:10:00 2006 From: Marcin.Ciura at NOSPAM.poczta.onet.pl (Marcin Ciura) Date: Fri, 09 Jun 2006 14:10:00 +0200 Subject: Large Dictionaries In-Reply-To: References: <1147699064.107490@teuthos> Message-ID: Duncan Booth wrote: > Marcin Ciura wrote: >>See Figure 8 in >>http://sun.iinf.polsl.gliwice.pl/~mciura/shellsort.pdf > That isn't what the reference says. It only covers N up to a few thousand. > Practical values of N need to at least go up into the millions. Please look at the performance graph of Tokuda's increment sequence. You can see that it scales pretty well at least up to 100 million. Marcin From duncan.booth at invalid.invalid Fri Jun 9 14:51:56 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Jun 2006 12:51:56 GMT Subject: Large Dictionaries References: <1147699064.107490@teuthos> Message-ID: Marcin Ciura wrote: > Duncan Booth wrote: >> Marcin Ciura wrote: >>>See Figure 8 in >>>http://sun.iinf.polsl.gliwice.pl/~mciura/shellsort.pdf >> That isn't what the reference says. It only covers N up to a few >> thousand. Practical values of N need to at least go up into the >> millions. > > Please look at the performance graph of Tokuda's increment sequence. > You can see that it scales pretty well at least up to 100 million. Ah sorry, I misread it. It was sequences with several thousand elements, which corresponds to N of 100 million. From mike.klaas at gmail.com Tue Jun 13 01:44:24 2006 From: mike.klaas at gmail.com (Klaas) Date: 12 Jun 2006 16:44:24 -0700 Subject: Large Dictionaries In-Reply-To: References: <1147699064.107490@teuthos> <1147772420.405097@teuthos> <1147818548.532882.94180@i39g2000cwa.googlegroups.com> <1147874585.728471@teuthos> <1148514158.790760.205630@i40g2000cwc.googlegroups.com> Message-ID: <1150155864.813698.206600@y43g2000cwc.googlegroups.com> Thomas Ganss wrote: > Klaas schrieb: > > > 4. Insert your keys in sorted order. > This advice is questionable - > it depends on the at least on the db vendor and probably > sometimes on the sort method, if inserting pre-sorted > values is better. The article I wrote that you quoted named a specific vendor (berkeley db) for which my advice is unquestionable and well-known. -Mike 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 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 sekhon.hari at googlemail.com Wed Jun 21 12:59:21 2006 From: sekhon.hari at googlemail.com (Hari Sekhon) Date: Wed, 21 Jun 2006 11:59:21 +0100 Subject: memory error with zipfile module In-Reply-To: <446e51e6$0$6831$636a55ce@news.free.fr> References: <446e07ab$0$12795$636a55ce@news.free.fr> <1148072514.207383.26370@j55g2000cwa.googlegroups.com> <446e51e6$0$6831$636a55ce@news.free.fr> Message-ID: On 20/05/06, Bruno Desthuilliers wrote: > > Roger Miller a ?crit : > > The basic problem is that the zipfile interface only reads and writes > > whole files, so it may perform poorly or fail on huge files. At one > > time I implemented a patch to allow reading files in chunks. However I > > believe that the current interface has too many problems to solve by > > incremental patching, > > Yeps, that was the general tone of some thread on python-dev. And from > what I saw of the source code, it may effectively not be the cleanest > part of the stdlib. But what, it does what it was written for at first : > provide working support for zipped packages. > > > and that a zipfile2 module is probably warranted. > > (Is anyone working on this?) > > Seems like Bob Ippolito was on the rank, but I guess you'll get better > answers on python-dev. > > > In the meantime I think the best solution is often to just run an > > external zip/unzip utility to do the heavy lifting. > > Indeed !-) > > But while having zip/unzip installed OOTB on a unix-like system is close > to warrented, it may not be the case on Windows. > -- > http://mail.python.org/mailman/listinfo/python-list > Shame, I would like to try to improve this but seeing as Roger Miller has already submitted a patch I don't know how much I can do for this. In the end I resorted to using an external zip utility via os.system(). I'll be interested to know if there is any work done on improving this as I'm in favour of native python usage, rather than using os.system() and relying on the operating system having a zip command, which I'm not convinced is the case on all windows machines, and also, I'm sure gentoo installs don't have zip by default, since I had to emerge it on a server for this script to work. Is it me or is having to use os.system() all the time symtomatic of a deficiency/things which are missing from python as a language? Not that I'm complaining, I'm just curious... I'm a fledgeling programmer so I don't mind being gently corrected by any veterans around. Hari -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Wed Jun 21 17:29:59 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 21 Jun 2006 17:29:59 +0200 Subject: memory error with zipfile module In-Reply-To: References: <446e07ab$0$12795$636a55ce@news.free.fr> <1148072514.207383.26370@j55g2000cwa.googlegroups.com> <446e51e6$0$6831$636a55ce@news.free.fr> Message-ID: Hari Sekhon wrote: > Is it me or is having to use os.system() all the time symtomatic of a > deficiency/things which are missing from python as a language? it's you. From sekhon.hari at googlemail.com Wed Jun 21 17:41:17 2006 From: sekhon.hari at googlemail.com (Hari Sekhon) Date: Wed, 21 Jun 2006 16:41:17 +0100 Subject: memory error with zipfile module In-Reply-To: References: <446e07ab$0$12795$636a55ce@news.free.fr> <1148072514.207383.26370@j55g2000cwa.googlegroups.com> <446e51e6$0$6831$636a55ce@news.free.fr> Message-ID: <4499689D.1000206@gmail.com> Fredrik Lundh wrote: > Hari Sekhon wrote: > > >> Is it me or is having to use os.system() all the time symtomatic of a >> deficiency/things which are missing from python as a language? >> > > it's you. > > > > I take it that it's still a work in progress to be able to pythonify everything, and until then we're just gonna have to rely on shell and those great C coded coreutils and stuff like that. Ok, I'm rather fond of Bash+coreutils, highest ratio of code lines to work I've ever seen.... it's the real strength of Linux. Shame about Windows... -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Wed Jun 21 17:51:21 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 21 Jun 2006 17:51:21 +0200 Subject: memory error with zipfile module In-Reply-To: <4499689D.1000206@gmail.com> References: <446e07ab$0$12795$636a55ce@news.free.fr> <1148072514.207383.26370@j55g2000cwa.googlegroups.com> <446e51e6$0$6831$636a55ce@news.free.fr> <4499689D.1000206@gmail.com> Message-ID: Hari Sekhon wrote: > I take it that it's still a work in progress to be able to pythonify > everything, and until then we're just gonna have to rely on shell and > those great C coded coreutils and stuff like that. Ok, I'm rather fond > of Bash+coreutils, highest ratio of code lines to work I've ever > seen.... it's the real strength of Linux. Shame about Windows... you make very little sense. From sekhon.hari at googlemail.com Wed Jun 21 18:02:24 2006 From: sekhon.hari at googlemail.com (Hari Sekhon) Date: Wed, 21 Jun 2006 17:02:24 +0100 Subject: memory error with zipfile module In-Reply-To: References: <446e07ab$0$12795$636a55ce@news.free.fr> <1148072514.207383.26370@j55g2000cwa.googlegroups.com> <446e51e6$0$6831$636a55ce@news.free.fr> <4499689D.1000206@gmail.com> Message-ID: <44996D90.4000802@gmail.com> Fredrik Lundh wrote: > Hari Sekhon wrote: > > >> I take it that it's still a work in progress to be able to pythonify >> everything, and until then we're just gonna have to rely on shell and >> those great C coded coreutils and stuff like that. Ok, I'm rather fond >> of Bash+coreutils, highest ratio of code lines to work I've ever >> seen.... it's the real strength of Linux. Shame about Windows... >> > > you make very little sense. > > > > how so, this is effectively what we do when we run os.system(). Usually people are running system commands on unix like machines using coreutils written in C to do things that are either difficult or near impossible to do in python... I've seen people using everything from zip to touch, either out of laziness or out of the fact it wouldn't work very well in python, this zip case is a good example. Sometimes when doing system scripts, they're effectively Bash scripting, but taking longer to do in many more lines of code cos it's in python. That makes very little sense. -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Wed Jun 21 18:34:51 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 21 Jun 2006 18:34:51 +0200 Subject: memory error with zipfile module In-Reply-To: <44996D90.4000802@gmail.com> References: <446e07ab$0$12795$636a55ce@news.free.fr> <1148072514.207383.26370@j55g2000cwa.googlegroups.com> <446e51e6$0$6831$636a55ce@news.free.fr> <4499689D.1000206@gmail.com> <44996D90.4000802@gmail.com> Message-ID: Hari Sekhon wrote: > I've seen people using everything from zip to touch, either out of > laziness or out of the fact it wouldn't work very well in python, this > zip case is a good example. so based on a limitation in one library, and some random code you've seen on the internet, you're making generalizations about the language ? the zip case is a pretty lousy example, btw; after all, using the existing API, it's not that hard to implement an *incremental* read function if the provided read-into-string version isn't sufficient: import zipfile, zlib ## # Given a 'zip' instance, copy data from the 'name' to the # 'out' stream. def explode(out, zip, name): zinfo = zip.getinfo(name) if zinfo.compress_type == zipfile.ZIP_STORED: decoder = None elif zinfo.compress_type == zipfile.ZIP_DEFLATED: decoder = zlib.decompressobj(-zlib.MAX_WBITS) else: raise zipfile.BadZipFile("unsupported compression method") zip.fp.seek(zinfo.file_offset) size = zinfo.compress_size while 1: data = zip.fp.read(min(size, 8192)) if not data: break size -= len(data) if decoder: data = decoder.decompress(data) out.write(data) if decoder: out.write(decoder.decompress('Z')) out.write(decoder.flush()) From SeaFuncSpam at gmail.com Sun Jun 11 05:59:03 2006 From: SeaFuncSpam at gmail.com (Mallor) Date: 10 Jun 2006 20:59:03 -0700 Subject: Xah Lee network abuse In-Reply-To: <1148495974.975395.12920@i40g2000cwc.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> Message-ID: <1149998343.493200.144990@h76g2000cwa.googlegroups.com> PofN wrote: > > Liar. You were never sorry when you troubled us with your posting > excrements in the past, you are not sorry now. > > Liar. You are a net abuser, a kook and a troll. It has nothing to do > with your writings and style. It has everything to do with your > vialoation of netiquette, with you x-posting of off-topic messages, > with your trolling and kookery. > > Liear. John asked people do do their duty as net citizens and to report > a serial net abuser. > > Liar. Your whole usenet "career" is build around the posting of > off-topic messages. > > Liar. You were getting out of hand for some time now. > > People know very well about you, Xah Lee, the serial newsgroup abuser, > troll, liar, and kook. > > More lies. > > I appreciate the courage of John and friends to stand up against > someone who is out of control. You are not even affraid off accusing > John of a crime (harrasment) and starting a smear campaing on your web > site. You have sunken so low that you are fast approaching the earth's > metal core. I know I'm coming late to the barbeque. In passing, I ask: do you have an objective, impartial perspective on the subject of committing crimes? Because libel is a crime. It all depends on whether what you state about Xah is provably true or not. I haven't followed his posts, but when I hear someone chanting "abuser, troll, liar, kook!" I really wonder about the accuser. Anyways, I suppose it's all "sport" until one of you gets the lawyers involved. Cheers, Brandon Van Every From max at alcyone.com Sun Jun 11 06:09:53 2006 From: max at alcyone.com (Erik Max Francis) Date: Sat, 10 Jun 2006 21:09:53 -0700 Subject: Xah Lee network abuse In-Reply-To: <1149998343.493200.144990@h76g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: Mallor wrote: > I know I'm coming late to the barbeque. In passing, I ask: do you have > an objective, impartial perspective on the subject of committing > crimes? Because libel is a crime. No, it is a tort. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Bachelors have consciences, married men have wives. -- H.L. Mencken From flippa at flippac.org Sun Jun 11 06:14:42 2006 From: flippa at flippac.org (Philippa Cowderoy) Date: Sun, 11 Jun 2006 05:14:42 +0100 Subject: Xah Lee network abuse In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: On Sat, 10 Jun 2006, Erik Max Francis wrote: > Mallor wrote: > > > I know I'm coming late to the barbeque. In passing, I ask: do you have > > an objective, impartial perspective on the subject of committing > > crimes? Because libel is a crime. > > No, it is a tort. > Rather a lot depends on which legal system you're in, for a start. Including the standards of proof and who the onus is on. -- flippa at flippac.org Sometimes you gotta fight fire with fire. Most of the time you just get burnt worse though. From max at alcyone.com Sun Jun 11 06:17:45 2006 From: max at alcyone.com (Erik Max Francis) Date: Sat, 10 Jun 2006 21:17:45 -0700 Subject: Xah Lee network abuse In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: Philippa Cowderoy wrote: > Rather a lot depends on which legal system you're in, for a start. > Including the standards of proof and who the onus is on. Oh, no doubt. But I don't think there's any modern legal system in which it's a crime, rather than a tort. Is there? Anyway, it's certainly a tort in all relevant jurisdictions here. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Covenants without the sword are but words. -- Camden From flippa at flippac.org Sun Jun 11 06:35:09 2006 From: flippa at flippac.org (Philippa Cowderoy) Date: Sun, 11 Jun 2006 05:35:09 +0100 Subject: Xah Lee network abuse In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: On Sat, 10 Jun 2006, Erik Max Francis wrote: > Philippa Cowderoy wrote: > > > Rather a lot depends on which legal system you're in, for a start. Including > > the standards of proof and who the onus is on. > > Oh, no doubt. But I don't think there's any modern legal system in which it's > a crime, rather than a tort. Is there? > I'm not aware of a current legal system where it's the case, but I don't know the details of many of them. -- flippa at flippac.org A problem that's all in your head is still a problem. Brain damage is but one form of mind damage. From esmond.not.pitt at not.bigpond.com Sun Jun 11 08:51:29 2006 From: esmond.not.pitt at not.bigpond.com (EJP) Date: Sun, 11 Jun 2006 06:51:29 GMT Subject: Xah Lee network abuse In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: Philippa Cowderoy wrote: > I'm not aware of a current legal system where it's the case, but I don't > know the details of many of them. Many states have criminal as well as civil libel. http://en.wikipedia.org/wiki/Slander_and_libel From max at alcyone.com Sun Jun 11 09:11:01 2006 From: max at alcyone.com (Erik Max Francis) Date: Sun, 11 Jun 2006 00:11:01 -0700 Subject: Xah Lee network abuse In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: EJP wrote: > Many states have criminal as well as civil libel. > http://en.wikipedia.org/wiki/Slander_and_libel The idea of using Wikipedia to back up a legal point is rather amusing ... but still, none of the relevant parties involved live in countries which have any form of criminal libel. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis To perceive is to suffer. -- Aristotle From esmond.not.pitt at not.bigpond.com Sun Jun 11 12:49:22 2006 From: esmond.not.pitt at not.bigpond.com (EJP) Date: Sun, 11 Jun 2006 10:49:22 GMT Subject: Xah Lee network abuse In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: Erik Max Francis wrote: > EJP wrote: > >> Many states have criminal as well as civil libel. >> http://en.wikipedia.org/wiki/Slander_and_libel > > The idea of using Wikipedia to back up a legal point is rather amusing > ... but still, none of the relevant parties involved live in countries > which have any form of criminal libel. OK, OK, just proffered as information, not a conclusive proof. It's the *courts* that back up legal points of course, not anything said or found here. From efuzzyone at netscape.net Tue Jun 13 09:16:49 2006 From: efuzzyone at netscape.net (Surendra Singhi) Date: Tue, 13 Jun 2006 12:46:49 +0530 Subject: Xah Lee network abuse References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: Its not Xah Lee, who abuses the system. But people like "Erik Max Francis" and "Philippa Cowderoy" who carry on nonsense discussions across mailing lists. -- Surendra Singhi http://ssinghi.kreeti.com ,---- | WHY SHOULD WE SAVE TIGER? | Ans: Saving the tiger means saving mankind.. | | Help http://pudang.tripod.com/ | or https://secure.worldwildlife.org/forms/tiger_appeal_1.cfm `---- From sigzero at gmail.com Mon Jun 12 02:00:00 2006 From: sigzero at gmail.com (Robert Hicks) Date: 11 Jun 2006 17:00:00 -0700 Subject: Xah Lee network abuse In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: <1150070400.803537.163570@f6g2000cwb.googlegroups.com> Erik Max Francis wrote: > Mallor wrote: > > > I know I'm coming late to the barbeque. In passing, I ask: do you have > > an objective, impartial perspective on the subject of committing > > crimes? Because libel is a crime. > > No, it is a tort. > Can I have whipped cream and strawberries on that tort? :Robert From mscottschilling at hotmail.com Sun Jun 11 06:40:39 2006 From: mscottschilling at hotmail.com (Mike Schilling) Date: Sun, 11 Jun 2006 04:40:39 GMT Subject: Xah Lee network abuse References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: "Mallor" wrote in message news:1149998343.493200.144990 at h76g2000cwa.googlegroups.com... > > I know I'm coming late to the barbeque. In passing, I ask: do you have > an objective, impartial perspective on the subject of committing > crimes? Because libel is a crime. It all depends on whether what you > state about Xah is provably true or not. I'm not aware of any definition of libel that includes "making statements that are not provably true". From flippa at flippac.org Sun Jun 11 06:50:00 2006 From: flippa at flippac.org (Philippa Cowderoy) Date: Sun, 11 Jun 2006 05:50:00 +0100 Subject: Xah Lee network abuse In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: On Sun, 11 Jun 2006, Mike Schilling wrote: > I'm not aware of any definition of libel that includes "making statements > that are not provably true". > I believe UK law uses one that's close to it. -- flippa at flippac.org Society does not owe people jobs. Society owes it to itself to find people jobs. From mscottschilling at hotmail.com Sun Jun 11 08:05:22 2006 From: mscottschilling at hotmail.com (Mike Schilling) Date: Sun, 11 Jun 2006 06:05:22 GMT Subject: Xah Lee network abuse References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: "Philippa Cowderoy" wrote in message news:Pine.WNT.4.61.0606110548540.1652 at SLINKY... > On Sun, 11 Jun 2006, Mike Schilling wrote: > >> I'm not aware of any definition of libel that includes "making statements >> that are not provably true". >> > > I believe UK law uses one that's close to it. If I were to write, say, that Tony Blair's tax policy will lead to higher deficits, I could be convicted of libel? Even if that's true, it's not a priori provable. From max at alcyone.com Sun Jun 11 08:14:21 2006 From: max at alcyone.com (Erik Max Francis) Date: Sat, 10 Jun 2006 23:14:21 -0700 Subject: Xah Lee network abuse In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: Mike Schilling wrote: > If I were to write, say, that Tony Blair's tax policy will lead to higher > deficits, I could be convicted of libel? Even if that's true, it's not a > priori provable. I think what he was getting at is that, unlike many jurisdictions, writing something factually true is _not_ in and of itself a defense against a libel suit in the UK. As for the reverse side of the issue, in jurisdictions where it _is_ a defense, if one were to accuse him of being a pedophile but couldn't prove it, that would certainly be an actionable offense. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Twenty-four hours a day, three-hundred sixty-five days a year as Secretary of Defense, I lived the Cold War. -- Robert S. McNamara From flippa at flippac.org Sun Jun 11 08:57:04 2006 From: flippa at flippac.org (Philippa Cowderoy) Date: Sun, 11 Jun 2006 07:57:04 +0100 Subject: Xah Lee network abuse In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: On Sat, 10 Jun 2006, Erik Max Francis wrote: > Mike Schilling wrote: > > > If I were to write, say, that Tony Blair's tax policy will lead to higher > > deficits, I could be convicted of libel? Even if that's true, it's not a > > priori provable. > > I think what he was getting at is that, unlike many jurisdictions, writing > something factually true is _not_ in and of itself a defense against a libel > suit in the UK. > It is. However, the onus is on the defendant to show that it's true, rather than on the claimant to show that it's false. I assume the "he" refers to Brandon? -- flippa at flippac.org A problem that's all in your head is still a problem. Brain damage is but one form of mind damage. From max at alcyone.com Sun Jun 11 09:11:28 2006 From: max at alcyone.com (Erik Max Francis) Date: Sun, 11 Jun 2006 00:11:28 -0700 Subject: Xah Lee network abuse In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: Philippa Cowderoy wrote: > It is. However, the onus is on the defendant to show that it's true, > rather than on the claimant to show that it's false. That also depends on the jurisdiction. > I assume the "he" > refers to Brandon? No, I was referring to the person who he was replying to, i.e., you. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Twenty-four hours a day, three-hundred sixty-five days a year as Secretary of Defense, I lived the Cold War. -- Robert S. McNamara From flippa at flippac.org Sun Jun 11 09:25:54 2006 From: flippa at flippac.org (Philippa Cowderoy) Date: Sun, 11 Jun 2006 08:25:54 +0100 Subject: Xah Lee network abuse In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: On Sun, 11 Jun 2006, Erik Max Francis wrote: > Philippa Cowderoy wrote: > > > It is. However, the onus is on the defendant to show that it's true, rather > > than on the claimant to show that it's false. > > That also depends on the jurisdiction. > Hrmm, does that one differ in Scotland? > > I assume the "he" refers to Brandon? > > No, I was referring to the person who he was replying to, i.e., you. > Wrong pronoun, then. -- flippa at flippac.org Society does not owe people jobs. Society owes it to itself to find people jobs. From max at alcyone.com Sun Jun 11 09:55:34 2006 From: max at alcyone.com (Erik Max Francis) Date: Sun, 11 Jun 2006 00:55:34 -0700 Subject: Xah Lee network abuse In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: <5smdnb3j67LkURbZnZ2dnUVZ_qydnZ2d@speakeasy.net> Philippa Cowderoy wrote: > Hrmm, does that one differ in Scotland? I don't believe so. > Wrong pronoun, then. Well, your comment was challenged, and I offered a reasonable interpretation of what you might have meant (which indicated a more general point in any case, namely that libel law is not quite as simple as the original poster was making it out to be). If you don't wish to defend your position, that's fine, but pointing fingers is kind of weird at this stage. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis To perceive is to suffer. -- Aristotle From flippa at flippac.org Sun Jun 11 10:01:54 2006 From: flippa at flippac.org (Philippa Cowderoy) Date: Sun, 11 Jun 2006 09:01:54 +0100 Subject: Xah Lee network abuse In-Reply-To: <5smdnb3j67LkURbZnZ2dnUVZ_qydnZ2d@speakeasy.net> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> <5smdnb3j67LkURbZnZ2dnUVZ_qydnZ2d@speakeasy.net> Message-ID: On Sun, 11 Jun 2006, Erik Max Francis wrote: > Philippa Cowderoy wrote: > > > Hrmm, does that one differ in Scotland? > > I don't believe so. > My statement was intended in the context of UK law - I have to admit to not knowing too much about what's different north of the border beyond the infamous verdict though. > > Wrong pronoun, then. > > Well, your comment was challenged, and I offered a reasonable interpretation > of what you might have meant (which indicated a more general point in any > case, namely that libel law is not quite as simple as the original poster was > making it out to be). If you don't wish to defend your position, that's fine, > but pointing fingers is kind of weird at this stage. > I'd still appreciate being referred to as "she" rather than "he" though. -- flippa at flippac.org 'In Ankh-Morpork even the shit have a street to itself... Truly this is a land of opportunity.' - Detritus, Men at Arms From max at alcyone.com Sun Jun 11 10:12:52 2006 From: max at alcyone.com (Erik Max Francis) Date: Sun, 11 Jun 2006 01:12:52 -0700 Subject: Xah Lee network abuse In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> <5smdnb3j67LkURbZnZ2dnUVZ_qydnZ2d@speakeasy.net> Message-ID: Philippa Cowderoy wrote: > I'd still appreciate being referred to as "she" rather than "he" though. Oops, my bad. Never occurred to me after all these years, which is kind of embarrassing, actually :-). -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Isn't jumping of a bridge / Free fallin' -- Sandra St. Victor From mscottschilling at hotmail.com Sun Jun 11 17:04:58 2006 From: mscottschilling at hotmail.com (Mike Schilling) Date: Sun, 11 Jun 2006 15:04:58 GMT Subject: Xah Lee network abuse References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: "Erik Max Francis" wrote in message news:qKmdnUvjhOZZKRbZnZ2dnUVZ_r-dnZ2d at speakeasy.net... > Mike Schilling wrote: > >> If I were to write, say, that Tony Blair's tax policy will lead to higher >> deficits, I could be convicted of libel? Even if that's true, it's not a >> priori provable. > > I think what he was getting at is that, unlike many jurisdictions, writing > something factually true is _not_ in and of itself a defense against a > libel suit in the UK. > > As for the reverse side of the issue, in jurisdictions where it _is_ a > defense, if one were to accuse him of being a pedophile but couldn't prove > it, that would certainly be an actionable offense. In the U.S, for instance, you wouldn't have to prove it. It would be sufficent to demonstrate that there's enough evidence supporting it that you weren't reckless in writing it. From gneuner2/ at comcast.net Mon Jun 12 00:20:42 2006 From: gneuner2/ at comcast.net (George Neuner) Date: Sun, 11 Jun 2006 18:20:42 -0400 Subject: Xah Lee network abuse References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: <8d2p82pq930hq4klnhbidr0i1t0hd8hqq2@4ax.com> On Sun, 11 Jun 2006 06:05:22 GMT, "Mike Schilling" wrote: > >"Philippa Cowderoy" wrote in message >news:Pine.WNT.4.61.0606110548540.1652 at SLINKY... >> On Sun, 11 Jun 2006, Mike Schilling wrote: >> >>> I'm not aware of any definition of libel that includes "making statements >>> that are not provably true". >> >> I believe UK law uses one that's close to it. > >If I were to write, say, that Tony Blair's tax policy will lead to higher >deficits, I could be convicted of libel? Even if that's true, it's not a >priori provable. DISCLAIMER - I AM NOT A LAWYER In the US, the defense against a libel claim is to prove the statement or accusation is true. In the US, libel involves damage to someone's reputation by means of deliberately false statements or accusations. Expert opinion is explicitly protected from libel claims unless it malicious. Non-expert opinion is generally judged on the intent of the author. Unprovable supposition is generally held to be non-libelous, however unprovable accusation is not allowed. Moreover, in the US, political figures are explicitly denied some (but not all) libel protections because it is expected that their actions will cause some measure of public dissent. I don't know UK defamation law but I suspect it is quite similar to US law. In your polite example, your opinion of Tony Blair's policy would be unprovable supposition at the time of the writing (as would Blair's own) and would therefore not be libelous. However, if your opinion took an accusatory tone saying, for example, that he was increasing the public deficit to line his pockets, then you had better be right. George -- for email reply remove "/" from address From jurgenex at hotmail.com Sun Jun 11 07:40:30 2006 From: jurgenex at hotmail.com (Jürgen Exner) Date: Sun, 11 Jun 2006 05:40:30 GMT Subject: Xah Lee network abuse References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <1149998343.493200.144990@h76g2000cwa.googlegroups.com> Message-ID: Mallor wrote: > I know I'm coming late to the barbeque. That's why you are missing the history > In passing, I ask: do you > have an objective, impartial perspective on the subject of committing > crimes? Because libel is a crime. It all depends on whether what you > state about Xah is provably true or not. I haven't followed his > posts, Had you done so, then you wouldn't ask this question. jue From ilias at lazaridis.com Mon Jun 5 13:05:10 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Mon, 05 Jun 2006 14:05:10 +0300 Subject: John Bokma harassment In-Reply-To: <1149083474.097849.262460@i40g2000cwc.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1149083474.097849.262460@i40g2000cwc.googlegroups.com> Message-ID: Xah Lee wrote: > Thanks to the great many people who has written to my ISP in support of [...] > As to dreamhost my webhosting company canceling my account, i will try > to reason with them, and see what is the final outcome. They have the > legal right to kick me because in the contract that allowed them to do > so with 30 days advanced noticed and without cause. However, it is my > interest and my right, if they actually do kick me in the end, i'll try > to contact Electronic Frontier Foundation and Better Business bureau > for whatever advice or action i can solicit. Meanwhile, if you do know > a web hosting company that can take some 80 G of bandwidth/month for > less than $25 a month, please let me know! (i do hope if someone here > runs a hosting business and can host my site. I will certainly return > the favor.) [...] > Xah Lee wrote: [...] >> I wrote some full detail here: >> http://xahlee.org/Periodic_dosage_dir/t2/harassment.html >> >> If you believe this lobbying to my webhosting provider is unjust, >> please write to my web hosting provider abuse at dreamhost.com >> >> Your help is appreciated. Thank you. HOST - dreamhost.com / Liberality (Hosting, Basic Requirement) http://groups.google.com/group/comp.lang.python/browse_frm/thread/25618913752c457a . -- http://lazaridis.com From usenet at local.machine Mon Jun 5 14:11:34 2006 From: usenet at local.machine (=?ISO-8859-2?Q?Dra=BEen_Gemi=E6?=) Date: Mon, 05 Jun 2006 14:11:34 +0200 Subject: John Bokma harassment In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1149083474.097849.262460@i40g2000cwc.googlegroups.com> Message-ID: Ilias Lazaridis wrote: > Xah Lee wrote: >> for whatever advice or action i can solicit. Meanwhile, if you do know >> a web hosting company that can take some 80 G of bandwidth/month for >> less than $25 a month, please let me know! (i do hope if someone here >> runs a hosting business and can host my site. I will certainly return >> the favor.) 80 Gb/month ? He intends to write a lot of spam..... DG From stormtoad at gmail.com Tue Jun 6 01:21:01 2006 From: stormtoad at gmail.com (Stormcoder) Date: 5 Jun 2006 16:21:01 -0700 Subject: Software Needs Philosophers References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> Message-ID: <1149549661.721778.8200@i40g2000cwc.googlegroups.com> He means Lisp macros. Lisp macros are nothing like the crippled C++ macros that people tend to think of. Roedy Green wrote: > On 21 May 2006 02:15:31 -0700, "Xah Lee" wrote, > quoted or indirectly quoted someone who said : > > > Java has lots of macro languages, including C++'s preprocessor. What > it does not have is a sanctioned one. It has instead on-the-fly code > generation. See http://mindprod.com/jgloss/onthefly.html > > > -- > Canadian Mind Products, Roedy Green. > http://mindprod.com Java custom programming, consulting and coaching. From xah at xahlee.org Thu Jun 8 03:35:52 2006 From: xah at xahlee.org (Xah Lee) Date: 7 Jun 2006 18:35:52 -0700 Subject: =?utf-8?B?VGhlIE5hdHVyZSBvZiB0aGUg4oCcVW5peCBQaGlsb3NvcGh54oCd?= In-Reply-To: <1149080931.582431.95560@j55g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1149080931.582431.95560@j55g2000cwa.googlegroups.com> Message-ID: <1149730552.161534.121350@i40g2000cwc.googlegroups.com> The Nature of the ?Unix Philosophy? Xah Lee, 2006-05 In the computing industry, especially among unix community, we often hear that there's a ?Unix Philosophy?. In this essay, i dissect the nature and characterization of such ?unix philosophy?, as have been described by Brian Kernighan, Rob Pike, Dennis Ritchie, Ken Thompson, and Richard P Gabriel et al, and in recent years by Eric Raymond. There is no one definite set of priciples that is the so-called ?unix philosophy?, but rather, it consistest of various slogans developed over the decades by unix programers that purport to describe the way unix is supposed to have been designed. The characteristics include: ?keep it simple?, ?make it fast?, ?keep it small?, ?make it work on 99% of cases, but generality and correctness are less important?, ?diversity rules?, ?User interface is not important, raw power is good?, ?everything should be a file?, ?architecture is less important than immediate workability?. Often, these are expressed by chantible slogans that exhibits juvenile humor, such as ?small is beautiful?, ?KISS (Keep It Simple, Stupid)?. Suppose, we take a team of student programers to produce a large software system. When the software is done, give it to software critics to analyze and come up with some principles that characterize its design decisions, without disclosing the nature of the programers. The characterization of such software, will more or less fit the descriptions of the ?Unix Philosophy? as described in different ways by various unix celebrities. For example, it would focus on implementation simplicity as opposed to interface simplicity. It will not be consistent in user interface, but exhibits rawness. It would be correct only for most cases, as opposed to mathematically correct or generic. It would employee simplistic data structures and formats such as text-files, as opposed to a structured system or binary format that requires a spec. It would be speedy, but less on scalability. It would consists of many small programs, as opposed to one large system with inter-dependent components. It would be easy to patch and port, but difficult to upgrade its structure or adapt entirely new assumptions. The essence of this theory is that when a software is produced for real world use, it is necessary that it works in some acceptable way, otherwise the software will be continuously debugged and refined. A software system written by a bunch of student or otherwise under-educated programers, but refined long enough for acceptably practical, real world use, will necessarily develop characteristics that is known as the Unix Philosophy. ---- This article is archived at: http://xahlee.org/UnixResource_dir/writ/unix_phil.html Xah xah at xahlee.org ? http://xahlee.org/ From invalid at invalid.net Thu Jun 8 03:52:53 2006 From: invalid at invalid.net (Frank Silvermann) Date: Wed, 07 Jun 2006 21:52:53 -0400 Subject: The Nature of the =?UTF-8?B?4oCcVW5peCBQaGlsb3NvcGh54oCd?= In-Reply-To: <1149730552.161534.121350@i40g2000cwc.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1149080931.582431.95560@j55g2000cwa.googlegroups.com> <1149730552.161534.121350@i40g2000cwc.googlegroups.com> Message-ID: <4487822b$0$30709$ec3e2dad@news.usenetmonster.com> Xah Lee wrote: > The Nature of the ?Unix Philosophy? > > Xah Lee, 2006-05 > > In the computing industry, especially among unix community, we often > hear that there's a ?Unix Philosophy?. In this essay, i dissect the > nature and characterization of such ?unix philosophy?, as have been > described by Brian Kernighan, Rob Pike, Dennis Ritchie, Ken Thompson, > and Richard P Gabriel et al, and in recent years by Eric Raymond. > Unix Philosophy. > ---- > This article is archived at: > http://xahlee.org/UnixResource_dir/writ/unix_phil.html > > Xah > xah at xahlee.org > ? http://xahlee.org/ > Sigma may impress some, but it does not impress me until you realize that philosophers can't count. That you have lower-case for the first person nominative pronoun is one thing, but that you have a difference in subject versus predicate is certainly something that Confucious criticizes. frank ------------------ tja From kst-u at mib.org Thu Jun 8 04:21:42 2006 From: kst-u at mib.org (Keith Thompson) Date: Thu, 08 Jun 2006 02:21:42 GMT Subject: The Nature of the =?utf-8?q?=E2=80=9CUnix_Philosophy=E2=80=9D?= References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1149080931.582431.95560@j55g2000cwa.googlegroups.com> <1149730552.161534.121350@i40g2000cwc.googlegroups.com> Message-ID: "Xah Lee" writes: > The Nature of the ?Unix Philosophy? > > Xah Lee, 2006-05 ___________________ /| /| | | ||__|| | Please do | / O O\__ NOT | / \ feed the | / \ \ trolls | / _ \ \ ______________| / |\____\ \ || / | | | |\____/ || / \|_|_|/ \ __|| / / \ |____| || / | | /| | --| | | |// |____ --| * _ | |_|_|_| | \-/ *-- _--\ _ \ // | / _ \\ _ // | / * / \_ /- | - | | * ___ c_c_c_C/ \C_c_c_c____________ (If you *must* post followups, please drop comp.lang.c from the Newsgroups: header -- which doesn't imply that this is topical in any of the other newsgroups to which it's posted.) Xah: please consider creating your own newsgroup under alt.*. You can post your long essays there and (if you absolutely insist on doing so) post pointers to them elsewhere. -- Keith Thompson (The_Other_Keith) kst-u at mib.org San Diego Supercomputer Center <*> We must do something. This is something. Therefore, we must do this. From NOS at Utel.no Thu Jun 8 09:28:08 2006 From: NOS at Utel.no (=?UTF-8?B?Ik5pbHMgTy4gU2Vsw6VzZGFsIg==?=) Date: Thu, 08 Jun 2006 09:28:08 +0200 Subject: The Nature of the =?UTF-8?B?4oCcVW5peCBQaGlsb3NvcGh54oCd?= In-Reply-To: <1149730552.161534.121350@i40g2000cwc.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1149080931.582431.95560@j55g2000cwa.googlegroups.com> <1149730552.161534.121350@i40g2000cwc.googlegroups.com> Message-ID: <4487d188$1@news.broadpark.no> Xah Lee wrote: > The Nature of the ?Unix Philosophy? > > Xah Lee, 2006-05 > > In the computing industry, especially among unix community, we often > hear that there's a ?Unix Philosophy?. In this essay, i dissect the > nature and characterization of such ?unix philosophy?, as have been > described by Brian Kernighan, Rob Pike, Dennis Ritchie, Ken Thompson, > and Richard P Gabriel et al, and in recent years by Eric Raymond. > > There is no one definite set of priciples that is the so-called ?unix > philosophy?, but rather, it consistest of various slogans developed > over the decades by unix programers that purport to describe the way > unix is supposed to have been designed. The characteristics include: > ?keep it simple?, ?make it fast?, ?keep it small?, ?make > it work on 99% of cases, but generality and correctness are less > important?, ?diversity rules?, ?User interface is not > important, raw power is good?, ?everything should be a file?, > ?architecture is less important than immediate workability?. Often, > these are expressed by chantible slogans that exhibits juvenile humor, > such as ?small is beautiful?, ?KISS (Keep It Simple, Stupid)?. Perhaps you should take a peek at the ideas in Plan 9 from Bell Labs, which is a continuation of this philosophy, unlike the "modern" unix clones. From invalid at invalid.net Thu Jun 8 15:25:40 2006 From: invalid at invalid.net (Frank Silvermann) Date: Thu, 08 Jun 2006 09:25:40 -0400 Subject: The Nature of the =?UTF-8?B?4oCcVW5peCBQaGlsb3NvcGh54oCd?= In-Reply-To: <4487d188$1@news.broadpark.no> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1149080931.582431.95560@j55g2000cwa.googlegroups.com> <1149730552.161534.121350@i40g2000cwc.googlegroups.com> <4487d188$1@news.broadpark.no> Message-ID: <44882412$0$20779$ec3e2dad@news.usenetmonster.com> Nils O. Sel?sdal wrote: > Xah Lee wrote: >> The Nature of the ?Unix Philosophy? [snip] > Perhaps you should take a peek at the ideas in Plan 9 from Bell Labs, > which is a continuation of this philosophy, unlike the "modern" unix > clones. Is there an actual Plan 9? I'm only aware of the one from Outer Space. frank From rlb at hoekstra-uitgeverij.nl Thu Jun 8 15:41:13 2006 From: rlb at hoekstra-uitgeverij.nl (Richard Bos) Date: Thu, 08 Jun 2006 13:41:13 GMT Subject: The Nature of the =?UTF-8?B?4oCcVW5peCBQaGlsb3NvcGh54oCd?= References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1149080931.582431.95560@j55g2000cwa.googlegroups.com> <1149730552.161534.121350@i40g2000cwc.googlegroups.com> <4487d188$1@news.broadpark.no> <44882412$0$20779$ec3e2dad@news.usenetmonster.com> Message-ID: <448828bb.84747014@news.xs4all.nl> Frank Silvermann wrote: > Nils O. Sel??sdal wrote: > > Xah Lee wrote: > >> The Nature of the ???Unix Philosophy??? > > > Perhaps you should take a peek at the ideas in Plan 9 from Bell Labs, > > which is a continuation of this philosophy, unlike the "modern" unix > > clones. > Is there an actual Plan 9? I'm only aware of the one from Outer Space. . But directing the OP there would be futile, as is discussing such off-topic matter on comp.lang.c. Richard From william at 25thandClement.com Fri Jun 9 06:33:21 2006 From: william at 25thandClement.com (William Ahern) Date: Thu, 08 Jun 2006 21:33:21 -0700 Subject: The Nature of the =?iso-8859-13?q?=B4Unix_Philosophy=A1?= References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1149080931.582431.95560@j55g2000cwa.googlegroups.com> <1149730552.161534.121350@i40g2000cwc.googlegroups.com> <4487d188$1@news.broadpark.no> <44882412$0$20779$ec3e2dad@news.usenetmonster.com> <448828bb.84747014@news.xs4all.nl> Message-ID: On Thu, 08 Jun 2006 13:41:13 +0000, Richard Bos wrote: > Frank Silvermann wrote: > >> Nils O. Sel??sdal wrote: >> > Xah Lee wrote: >> >> The Nature of the ???Unix Philosophy??? >> >> > Perhaps you should take a peek at the ideas in Plan 9 from Bell Labs, >> > which is a continuation of this philosophy, unlike the "modern" unix >> > clones. >> Is there an actual Plan 9? I'm only aware of the one from Outer Space. > > . > > But directing the OP there would be futile, as is discussing such > off-topic matter on comp.lang.c. > > Richard Not totally off-topic. The Plan 9 "C" compiler supports some noteworthy additions and changes to the language. Certainly, in contrast, elucidative of standard C. Plus, you gotta love anonymous structures and unions ;) GCC supports them, and so does TinyCC I think. From pjb at informatimago.com Thu Jun 8 15:46:56 2006 From: pjb at informatimago.com (Pascal Bourguignon) Date: Thu, 08 Jun 2006 15:46:56 +0200 Subject: The Nature of the =?utf-8?Q?=E2=80=9CUnix_Philosophy=E2=80=9D?= References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1149080931.582431.95560@j55g2000cwa.googlegroups.com> <1149730552.161534.121350@i40g2000cwc.googlegroups.com> <4487d188$1@news.broadpark.no> <44882412$0$20779$ec3e2dad@news.usenetmonster.com> Message-ID: <878xo7sqsv.fsf@thalassa.informatimago.com> Frank Silvermann writes: > Nils O. Sel?sdal wrote: >> Xah Lee wrote: >>> The Nature of the ?Unix Philosophy? > [snip] > >> Perhaps you should take a peek at the ideas in Plan 9 from Bell Labs, >> which is a continuation of this philosophy, unlike the "modern" unix >> clones. > Is there an actual Plan 9? I'm only aware of the one from Outer > Space. frank No, there is no _actual_ Plan 9. The OS named "Plan 9" is named after the Outer Space one. -- __Pascal Bourguignon__ http://www.informatimago.com/ ATTENTION: Despite any other listing of product contents found herein, the consumer is advised that, in actuality, this product consists of 99.9999999999% empty space. From albalmer at att.net Thu Jun 8 18:21:44 2006 From: albalmer at att.net (Al Balmer) Date: Thu, 08 Jun 2006 16:21:44 GMT Subject: The Nature of the “Unix Philosophy” References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1149080931.582431.95560@j55g2000cwa.googlegroups.com> <1149730552.161534.121350@i40g2000cwc.googlegroups.com> Message-ID: On 7 Jun 2006 18:35:52 -0700, "Xah Lee" wrote: >The Nature of the ?Unix Philosophy? Good grief. Him again. -- Al Balmer Sun City, AZ 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 ibr at radix50.net Sat Jun 3 13:04:10 2006 From: ibr at radix50.net (Baurzhan Ismagulov) Date: Sat, 3 Jun 2006 13:04:10 +0200 Subject: logging In-Reply-To: <1149113113.083677.235570@i39g2000cwa.googlegroups.com> References: <1148426018.334087.124160@i40g2000cwc.googlegroups.com> <1148577240.250304.116360@j55g2000cwa.googlegroups.com> <1149005605.819519.242350@j55g2000cwa.googlegroups.com> <1149113113.083677.235570@i39g2000cwa.googlegroups.com> Message-ID: <20060603110410.GA30398@radix50.net> Hello Vinay, On Wed, May 31, 2006 at 03:05:13PM -0700, Vinay Sajip wrote: > > 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. ... Thanks for the explanation! Please note that I am not questioning the usefulness of hierarchical logging -- I think it's a Good Thing. What I can't understand is the motivation for the single place of decision whether a message should be printed ("is enabled" in log4j terms) or not. Consider the following scenario: root is CRITICAL, l01 is DEBUG, a debug message is logged on l01. l01 decides that the message should be printed, and _both_ root and l01 print it. Now, it is good that the message is propagated to root, but why doesn't root decide for itself whether to print it or not? For instance, I log root to syslog and have only critical messages there. I log l01 to console to debug. I want that my message to l01 is not printed by root since its level is CRITICAL. This is why I want that each logger re-evaluates the message level for itself. Could you perhaps give a useful example why one could want loggers to decide once? And another thing I couldn't find how to do: I want to have several debug levels. I can log messages without problems, but numeric values in the configuration file cause error messages during logging.config.fileConfig. Can I specify numeric values in the config file? With kind regards, Baurzhan. From vinay_sajip at yahoo.co.uk Sun Jun 4 14:23:55 2006 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 4 Jun 2006 05:23:55 -0700 Subject: logging References: <1148426018.334087.124160@i40g2000cwc.googlegroups.com> <1148577240.250304.116360@j55g2000cwa.googlegroups.com> <1149005605.819519.242350@j55g2000cwa.googlegroups.com> <1149113113.083677.235570@i39g2000cwa.googlegroups.com> Message-ID: <1149423835.166446.126240@i40g2000cwc.googlegroups.com> Hello Baurzhan, > Consider the following scenario: root is CRITICAL, l01 is DEBUG, a debug > message is logged on l01. l01 decides that the message should be > printed, and _both_ root and l01 print it. Now, it is good that the > message is propagated to root, but why doesn't root decide for itself > whether to print it or not? It's not propagated to the root logger (or to ancestor loggers in general) - just to the handlers associated with ancestor loggers. > For instance, I log root to syslog and have only critical messages > there. I log l01 to console to debug. I want that my message to l01 is > not printed by root since its level is CRITICAL. This is why I want that > each logger re-evaluates the message level for itself. Could you perhaps > give a useful example why one could want loggers to decide once? You can set levels on handlers as well as loggers. So if you add a syslog handler to the root and set its level to CRITICAL, only CRITICAL messages are sent to syslog. > And another thing I couldn't find how to do: I want to have several > debug levels. I can log messages without problems, but numeric values in > the configuration file cause error messages during > logging.config.fileConfig. Can I specify numeric values in the config > file? You should use addLevelName to add custom levels. You can do e.g. logging.MYCUSTOMLEVEL = 25 logging.addLevelName(logging.MYCUSTOMLEVEL, "MYCUSTOMLEVEL") and then reference MYCUSTOMLEVEL in the config file. Regards, Vinay From ibr at radix50.net Mon Jun 5 19:19:51 2006 From: ibr at radix50.net (Baurzhan Ismagulov) Date: Mon, 5 Jun 2006 19:19:51 +0200 Subject: logging In-Reply-To: <1149423835.166446.126240@i40g2000cwc.googlegroups.com> References: <1148426018.334087.124160@i40g2000cwc.googlegroups.com> <1148577240.250304.116360@j55g2000cwa.googlegroups.com> <1149005605.819519.242350@j55g2000cwa.googlegroups.com> <1149113113.083677.235570@i39g2000cwa.googlegroups.com> <1149423835.166446.126240@i40g2000cwc.googlegroups.com> Message-ID: <20060605171951.GA14461@radix50.net> Hello Vinay, On Sun, Jun 04, 2006 at 05:23:55AM -0700, Vinay Sajip wrote: > It's not propagated to the root logger (or to ancestor loggers in > general) - just to the handlers associated with ancestor loggers. ... > You can set levels on handlers as well as loggers. So if you add a > syslog handler to the root and set its level to CRITICAL, only CRITICAL > messages are sent to syslog. ... > logging.MYCUSTOMLEVEL = 25 > logging.addLevelName(logging.MYCUSTOMLEVEL, "MYCUSTOMLEVEL") Thanks much! With kind regards, Baurzhan. From martin.wiechert at gmx.de Sun Jun 4 16:17:08 2006 From: martin.wiechert at gmx.de (Martin Wiechert) Date: Sun, 04 Jun 2006 16:17:08 +0200 Subject: linking errors with debug build of Python2.4.3 In-Reply-To: <1148781211.487215.260090@j73g2000cwa.googlegroups.com> References: <1148781211.487215.260090@j73g2000cwa.googlegroups.com> Message-ID: <200606041617.09198.martin.wiechert@gmx.de> You were right, leaving out --with-pydebug did the trick. Thanks, Martin On Sunday 28 May 2006 03:53, nnorwitz at gmail.com wrote: > Martin Wiechert wrote: > > Hi list, > > > > I've created a fresh build of Python 2.4.3 using the following > > configuration > > > > $ ./configure --with-pydebug --prefix=/usr/local/debug --enable-shared > > --with-fpectl --with-signal-module > > > > What did I do wrong? > > Try with just: ./configure --with-pydebug --prefix=/usr/local/debug > > I think the problem is --enable-shared. I'm not sure what you are > doing, but you probably don't need the other options. The signal > module should always be built, I've never even seen the > --with-signal-module option. :-) > > n From martin.wiechert at gmx.de Mon Jun 5 19:47:30 2006 From: martin.wiechert at gmx.de (Martin Wiechert) Date: Mon, 05 Jun 2006 19:47:30 +0200 Subject: linking errors with debug build of Python2.4.3 In-Reply-To: <200606041617.09198.martin.wiechert@gmx.de> References: <1148781211.487215.260090@j73g2000cwa.googlegroups.com> <200606041617.09198.martin.wiechert@gmx.de> Message-ID: <200606051947.31136.martin.wiechert@gmx.de> Nonsense! I meant leaving out --enable-shared. On Sunday 04 June 2006 16:17, Martin Wiechert wrote: > You were right, leaving out --with-pydebug did the trick. > > Thanks, Martin > > On Sunday 28 May 2006 03:53, nnorwitz at gmail.com wrote: > > Martin Wiechert wrote: > > > Hi list, > > > > > > I've created a fresh build of Python 2.4.3 using the following > > > configuration > > > > > > $ ./configure --with-pydebug --prefix=/usr/local/debug --enable-shared > > > --with-fpectl --with-signal-module > > > > > > What did I do wrong? > > > > Try with just: ./configure --with-pydebug --prefix=/usr/local/debug > > > > I think the problem is --enable-shared. I'm not sure what you are > > doing, but you probably don't need the other options. The signal > > module should always be built, I've never even seen the > > --with-signal-module option. :-) > > > > n 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 jjlee at reportlab.com Mon Jun 5 21:14:59 2006 From: jjlee at reportlab.com (John J. Lee) Date: Mon, 05 Jun 2006 19:14:59 GMT Subject: urllib2 and HTTP 302 References: <4476C7A6.5040506@designaproduct.biz> Message-ID: <873beje7nw.fsf@reportlab.com> jjl at pobox.com (John J. Lee) writes: > 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() Sorry, didn't read that properly. If your OpenerDirector instance has an HTTPRedirectHandler, you should be able to get the final redirected URL the way I said (using .geturl()). If it doesn't (which I assume is true in your case -- why else would you be checking for a 302 status), well, you just have to do exactly the same thing that HTTPRedirectHandler does :-) Use the source luke. John 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 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 sekhon.hari at googlemail.com Wed Jun 21 12:44:32 2006 From: sekhon.hari at googlemail.com (Hari Sekhon) Date: Wed, 21 Jun 2006 11:44:32 +0100 Subject: WinPops In-Reply-To: <447f5781$0$15793$14726298@news.sunsite.dk> References: <1149132789_5889@sp6iad.superfeed.net> <447f5781$0$15793$14726298@news.sunsite.dk> Message-ID: If you were going to do this you may as well just do something like if sys.platform='win32': os.system('net send ') elif sys.platform[:5]='linux' os.system('smblcient -M etc...') This would be more portable and simpler than the alternatives I've seen. It would be better if there was just a cross platform library for this protocol so you could just import winpop winpop.send (host,message) Too much to ask? Hari On 01/06/06, Peter Gsellmann wrote: > > 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 > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: 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 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 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 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 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 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 michele.petrazzo at TOGLIunipex.it Sat Jun 3 11:13:46 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Sat, 03 Jun 2006 09:13:46 GMT Subject: Trying to get FreeImagePy to work. In-Reply-To: <1149235836.646855.164110@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> <3PCfg.20835$cX1.315781@twister2.libero.it> <1149174938.337973.85950@g10g2000cwb.googlegroups.com> <1149192520.959302.250840@j55g2000cwa.googlegroups.com> <1149235836.646855.164110@i40g2000cwc.googlegroups.com> Message-ID: Iain King wrote: >> 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 > Yes it's min-is-white:: michele:~$ tiffinfo example.tif TIFFReadDirectory: Warning, example.tif: unknown field with tag 37680 (0x9330) encountered. TIFF Directory at offset 0x1520 (5408) Subfile Type: (0 = 0x0) Image Width: 1696 Image Length: 1162 Resolution: 200, 200 pixels/inch Bits/Sample: 1 Compression Scheme: CCITT Group 4 Photometric Interpretation: min-is-white # <------ FillOrder: msb-to-lsb Samples/Pixel: 1 Rows/Strip: 1162 Planar Configuration: single image plane ImageDescription: DS michele:~$ So you *need* to invert it to work correctly with PIL! P.s. Added the convertToWx function, that return a wx.Image, to the Image class. Michele From iainking at gmail.com Mon Jun 5 10:11:14 2006 From: iainking at gmail.com (Iain King) Date: 5 Jun 2006 01:11:14 -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> <1149192520.959302.250840@j55g2000cwa.googlegroups.com> <1149235836.646855.164110@i40g2000cwc.googlegroups.com> Message-ID: <1149495074.808694.273010@j55g2000cwa.googlegroups.com> Michele Petrazzo wrote: > Iain King wrote: > >> 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 > > > > Yes it's min-is-white:: > > michele:~$ tiffinfo example.tif > TIFFReadDirectory: Warning, example.tif: unknown field with tag 37680 > (0x9330) encountered. > TIFF Directory at offset 0x1520 (5408) > Subfile Type: (0 = 0x0) > Image Width: 1696 Image Length: 1162 > Resolution: 200, 200 pixels/inch > Bits/Sample: 1 > Compression Scheme: CCITT Group 4 > Photometric Interpretation: min-is-white # <------ > FillOrder: msb-to-lsb > Samples/Pixel: 1 > Rows/Strip: 1162 > Planar Configuration: single image plane > ImageDescription: DS > michele:~$ > > So you *need* to invert it to work correctly with PIL! > > P.s. Added the convertToWx function, that return a wx.Image, to the > Image class. > > Michele Most excellent! Iain From fredrik at pythonware.com Mon Jun 5 10:49:37 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 05 Jun 2006 10:49:37 +0200 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> <1149192520.959302.250840@j55g2000cwa.googlegroups.com> <1149235836.646855.164110@i40g2000cwc.googlegroups.com> Message-ID: Michele Petrazzo wrote: > Yes it's min-is-white:: > > michele:~$ tiffinfo example.tif > TIFFReadDirectory: Warning, example.tif: unknown field with tag 37680 > (0x9330) encountered. > TIFF Directory at offset 0x1520 (5408) > Subfile Type: (0 = 0x0) > Image Width: 1696 Image Length: 1162 > Resolution: 200, 200 pixels/inch > Bits/Sample: 1 > Compression Scheme: CCITT Group 4 > Photometric Interpretation: min-is-white # <------ > FillOrder: msb-to-lsb > Samples/Pixel: 1 > Rows/Strip: 1162 > Planar Configuration: single image plane > ImageDescription: DS > michele:~$ > > So you *need* to invert it to work correctly with PIL! PIL has no problem reading "min-is-white" TIFF images. it would be nice if you stopped posting bogus "support" information for other libraries. From michele.petrazzo at TOGLIunipex.it Mon Jun 5 11:16:03 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Mon, 05 Jun 2006 09:16:03 GMT 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> <1149192520.959302.250840@j55g2000cwa.googlegroups.com> <1149235836.646855.164110@i40g2000cwc.googlegroups.com> Message-ID: Fredrik Lundh wrote: >> So you *need* to invert it to work correctly with PIL! > > PIL has no problem reading "min-is-white" TIFF images. > > it would be nice if you stopped posting bogus "support" information > for other libraries. Sorry if my posts make to seem that other libraries has problems! Sure that *my* wrap has problems, like I have problem with something that I don't know so well, like Image world (like I always said). I'm only suggesting some, bad, trick for do the work that "Iain" wants. I tried, but without success, to make the "convertToPil" function work with 1, 8, 16 bpp... Seem that only 24/32 work, but I don't know why. I know that PIL doesn't have problems! > > > Hope that this can explain better the situation. Bye, Michele From ilias at lazaridis.com Sun Jun 4 15:17:54 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Sun, 04 Jun 2006 16:17:54 +0300 Subject: PUDGE - Project Status, Alternative Solutions In-Reply-To: <447786E9.9010208@lazaridis.com> References: <447786E9.9010208@lazaridis.com> Message-ID: <4482DD82.6010003@lazaridis.com> Ilias Lazaridis wrote: > What is going on with the pudge project? Any chance to get an comment on this? > Mr. Patrik O'Brien (Orbtech LLC) had told me that there is no similar > tool available within the python domain, thus I have invested some > effort to create a Website template, and to enable pudge to generate > colored code: > > http://audit.lazaridis.com/schevo/wiki/SchevoWebsiteReview > > I like to reuse the results for personal projects, but I am wondering > that the pudge email-list is death (since the server update) - and that > no one of the project reacts to personal and public postings. > > Additionally, the schevo project removes the pudge stuff, mscott, the > developer which has introduced pudge removes it again (although this was > done with several other tools in the past, too): > > http://schevo.org/trac/changeset/2127 > > - > > Is there a similar tool available, with which I can generate python > documentation / websites or both based on templates and reST? > > Or an overview of such tools? > > I mean such an organized tool is essential for developmente with python. > > . > -- http://lazaridis.com From ilias at lazaridis.com Wed Jun 7 17:45:38 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Wed, 07 Jun 2006 18:45:38 +0300 Subject: PUDGE - Project Status, Alternative Solutions In-Reply-To: <4482DD82.6010003@lazaridis.com> References: <447786E9.9010208@lazaridis.com> <4482DD82.6010003@lazaridis.com> Message-ID: <4486F4A2.1000906@lazaridis.com> Ilias Lazaridis wrote: > Ilias Lazaridis wrote: >> What is going on with the pudge project? > > Any chance to get an comment on this? After a little bit off-list discussion, I understand that many python documentation projects stop at some point, and that efforts are in general not very synchronized. Small overview here (work in progress): http://case.lazaridis.com/wiki/Docgen - btw: Still, the pudge.general list needs to be activated!!! >> Mr. Patrik O'Brien (Orbtech LLC) had told me that there is no similar >> tool available within the python domain, thus I have invested some >> effort to create a Website template, and to enable pudge to generate >> colored code: >> >> http://audit.lazaridis.com/schevo/wiki/SchevoWebsiteReview >> >> I like to reuse the results for personal projects, but I am wondering >> that the pudge email-list is death (since the server update) - and >> that no one of the project reacts to personal and public postings. >> >> Additionally, the schevo project removes the pudge stuff, mscott, the >> developer which has introduced pudge removes it again (although this >> was done with several other tools in the past, too): >> >> http://schevo.org/trac/changeset/2127 >> >> - >> >> Is there a similar tool available, with which I can generate python >> documentation / websites or both based on templates and reST? >> >> Or an overview of such tools? >> >> I mean such an organized tool is essential for developmente with python. >> >> . >> > > -- http://lazaridis.com From frank at niessink.com Mon Jun 5 11:01:43 2006 From: frank at niessink.com (Frank Niessink) Date: Mon, 05 Jun 2006 11:01:43 +0200 Subject: TreeCtrl to TreeListCtrl In-Reply-To: <20060527124212.23272.qmail@web33101.mail.mud.yahoo.com> References: <20060527124212.23272.qmail@web33101.mail.mud.yahoo.com> Message-ID: <4483F2F7.9080300@niessink.com> sendhil kumar: > Hi all, > whwn working with xml connectvity to python, i have a > sash window, in which first window has a Tree Control > that has 'n' parent fields preceded by + sign and on > leftdown all the childs got from external xml file. > > when the particular parent field is selected and > dragged, it must get posted to the other sash window > which should in TreeList Control, bcoz iam displaying > numerous xml attributes of the parent and following > 'n' number of childs from xml. > > Now, iam facing a problem in implementing with > TreeListCtrl, but it works fne with ListCtrl... And what exactly is your problem? Cheers, Frank From nick at craig-wood.com Mon Jun 5 12:30:07 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 05 Jun 2006 05:30:07 -0500 Subject: Best way to check that a process is running on a Unix system? References: <16de708d0605272205m66cbadc9h25e699fe4f7b32ec@mail.gmail.com> Message-ID: BJ?rn Lindqvist wrote: > > What is the best way to check that a process is running (or better yet > > number of instances) based on the name of the process? Would have to > > work on a unix/linux system. > > Use "ps -C proc_name". Then either read the nr of lines in the output > (for the number of instances) or read the return value. 0 if the > process is running. Or read the /proc/*/status files and check if your > process is in any of them. Here is a module I wrote ages ago which does the grubbling around in /proc for you. >>> import process >>> p = process.ProcessList() >>> p.named("emacs") [Process(pid = 20610), Process(pid = 6076), Process(pid = 6113), Process(pid = 6590), Process(pid = 857), Process(pid = 1394), Process(pid = 28974)] >>> Parsing the output of "ps -ef" will be more portable between unixes though! ------------------------------------------------------------ """ Manage Processes and a ProcessList under Linux. """ import os import signal class Process(object): """Represents a process""" def __init__(self, pid): """Make a new Process object""" self.proc = "/proc/%d" % pid pid,command,state,parent_pid = file(os.path.join(self.proc, "stat")).read().strip().split()[:4] command = command[1:-1] self.pid = int(pid) self.command = command self.state = state self.parent_pid = int(parent_pid) self.parent = None self.children = [] def kill(self, sig = signal.SIGTERM): """Kill this process with SIGTERM by default""" os.kill(self.pid, sig) def __repr__(self): return "Process(pid = %r)" % self.pid def getcwd(self): """Read the current directory of this process or None for can't""" try: return os.readlink(os.path.join(self.proc, "cwd")) except OSError: return None class ProcessList(object): """Represents a list of processes""" def __init__(self): """Read /proc and fill up the process lists""" self.by_pid = {} self.by_command = {} for f in os.listdir("/proc"): if f.isdigit(): process = Process(int(f)) self.by_pid[process.pid] = process self.by_command.setdefault(process.command, []).append(process) for process in self.by_pid.values(): try: parent = self.by_pid[process.parent_pid] #print "child",process #print "parent",parent parent.children.append(process) process.parent = parent except KeyError: pass def named(self, name): """Returns a list of processes with the given name""" return self.by_command.get(name, []) ------------------------------------------------------------ -- Nick Craig-Wood -- http://www.craig-wood.com/nick 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 ldo at geek-central.gen.new_zealand Mon Jun 5 11:29:53 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 05 Jun 2006 21:29:53 +1200 Subject: summarize text References: <1148903386.095226.249270@38g2000cwa.googlegroups.com> Message-ID: ... sorry, I thought you said "summarize Proust". :) From sdcook55 at sbcglobal.net Sun Jun 4 16:17:02 2006 From: sdcook55 at sbcglobal.net (Stan Cook) Date: Sun, 04 Jun 2006 14:17:02 GMT Subject: create a text file In-Reply-To: References: <2xIeg.88125$H71.14049@newssvr13.news.prodigy.com> Message-ID: Fredrik Lundh wrote: > Stan Cook wrote: > >> I'm writing a script to list all of my music files' id3 tags to a >> comma delimited file. The only part I'm missing seems like it should >> be the simplest. I haven't used Python for the last couple of years. >> My question is this: >> >> When I use os.open(,"w"), I get an error >> message, TypeError: an integer is required. Has something >> changed? Did I miss something??? > > the function is called "open", not "os.open". > > there's an open function in the os module, but that's doing something > slightly different (see the library reference documentation for details > if you're curious). > > > Thanks, I found it. 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 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 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 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 > 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 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 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 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 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 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 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 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 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 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 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 raNOsky at deveSPAMler.com Thu Jun 1 19:44:40 2006 From: raNOsky at deveSPAMler.com (Giovanni Bajo) Date: Thu, 1 Jun 2006 19:44:40 +0200 Subject: struct: type registration? References: <447e4b98$1@news.eftel.com> <447EDF7C.3080104@lexicon.net> Message-ID: 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. 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. Sorry if this confused you. 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. -- Giovanni Bajo 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 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 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(' <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(' 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 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 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 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 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 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 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 Bulkan at gmail.com Mon Jun 5 08:52:40 2006 From: Bulkan at gmail.com (placid) Date: 4 Jun 2006 23:52:40 -0700 Subject: Is device Connected Windows? In-Reply-To: References: Message-ID: <1149490360.147668.265590@u72g2000cwu.googlegroups.com> Tim Golden wrote: > [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 > > > Thanks mate, this is what i was after, i can work my way through here. 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: 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: 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 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 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 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 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 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 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 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 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 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: From spiralx at gmail.com Sat Jun 3 18:11:52 2006 From: spiralx at gmail.com (James) Date: Sat, 3 Jun 2006 17:11:52 +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: <7ee3dcd80606030911u71705a7bif44025cec773dbcc@mail.gmail.com> Any code which requires serious algorithmic work I write and test in Python before converting into Java - it's so much easier to use Python's datatypes and interpreter to get things right before having to deal with Java's clunky class libraries. James On 02/06/06, Norbert Kaufmann wrote: > 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 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 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 jzgoda at o2.usun.pl Fri Jun 2 21:53:27 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 02 Jun 2006 21:53:27 +0200 Subject: How do you practice Python? In-Reply-To: <1149271920.917381.112910@u72g2000cwu.googlegroups.com> References: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> <1149271920.917381.112910@u72g2000cwu.googlegroups.com> Message-ID: sjdevnull at yahoo.com napisa?(a): >>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. I second that. I moved from Python to J2EE in my job, but I didn't stop writing Python code for my spare-time projects. Now, when tight schedule made my project's manager to shift paradigm from buzz to productivity, I am happy I can write programs in Python again. On AS/400, but still better than Java... :D -- Jarek Zgoda http://jpa.berlios.de/ From samschul at pacbell.net Fri Jun 2 22:45:56 2006 From: samschul at pacbell.net (sam) Date: 2 Jun 2006 13:45:56 -0700 Subject: How do you practice Python? In-Reply-To: References: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> <1149271920.917381.112910@u72g2000cwu.googlegroups.com> Message-ID: <1149281156.712919.226210@g10g2000cwb.googlegroups.com> Years ago I developed a Hard Disk Drive diagnostic program "SCSIPython" while working for a disk drive company. When I left that company,and realized that these routines would never be used by the company, I released it as Open Source. Since then I have maintained this code, and enhanced it with the various versions of Python that have been released after V1.5. I find that with each update my code becomes more robust,with added features. Also As I moved from company to company I made certain that they knew that this code was Open Source,and only proprietary methods will be excluded, when I signed the standard intellectual property forms. Sam Schulenburg Jarek Zgoda wrote: > sjdevnull at yahoo.com napisa?(a): > > >>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. > > I second that. I moved from Python to J2EE in my job, but I didn't stop > writing Python code for my spare-time projects. Now, when tight schedule > made my project's manager to shift paradigm from buzz to productivity, I > am happy I can write programs in Python again. On AS/400, but still > better than Java... :D > > -- > Jarek Zgoda > http://jpa.berlios.de/ From spiralx at gmail.com Sat Jun 3 18:08:09 2006 From: spiralx at gmail.com (James) Date: Sat, 3 Jun 2006 17:08:09 +0100 Subject: How do you practice Python? In-Reply-To: References: <1149150517.034409.292530@g10g2000cwb.googlegroups.com> <1149271920.917381.112910@u72g2000cwu.googlegroups.com> Message-ID: <7ee3dcd80606030908nbd09943j8cf34c217e4cac07@mail.gmail.com> Thirded here. Perhaps better for me is that although I program client-side Java for my job, as much of the backend as possible I code in Python, which makes it easier to do a lot of data processing stuff much simpler than Java would. And it's let me use and understand all of the new features of the language... last time I did it for a job was in the days of Python 1.5.2. Being non-critical utilities on the backend means whenever new features are introduced I can upgrade my code to take advantage of them without worrying about things going wrong as well ;) James On 02/06/06, Jarek Zgoda wrote: > I second that. I moved from Python to J2EE in my job, but I didn't stop > writing Python code for my spare-time projects. Now, when tight schedule > made my project's manager to shift paradigm from buzz to productivity, I > am happy I can write programs in Python again. On AS/400, but still > better than Java... :D > > -- > Jarek Zgoda > http://jpa.berlios.de/ > -- > http://mail.python.org/mailman/listinfo/python-list > 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 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 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 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: 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 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 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 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 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 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 __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 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 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 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 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 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 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 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 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 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 __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 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 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 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 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 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 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 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 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 Serge.Orlov at gmail.com Thu Jun 1 20:02:44 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 1 Jun 2006 11:02:44 -0700 Subject: py2exe & qt4/qimage References: <1149163754.826678.95920@h76g2000cwa.googlegroups.com> Message-ID: <1149184964.329575.292450@y43g2000cwc.googlegroups.com> aljosa wrote: > 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? You need bundle the plugins as data files: http://docs.python.org/dist/node12.html 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 __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 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 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 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 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 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 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 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 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 duncanm255 at hotmail.com Mon Jun 5 17:32:10 2006 From: duncanm255 at hotmail.com (D) Date: 5 Jun 2006 08:32:10 -0700 Subject: Starting New Process In-Reply-To: <1149189887.279693.146240@f6g2000cwb.googlegroups.com> References: <1149172463.881528.131290@j55g2000cwa.googlegroups.com> <1149185284.820789.321130@y43g2000cwc.googlegroups.com> <1149189887.279693.146240@f6g2000cwb.googlegroups.com> Message-ID: <1149521530.000954.101520@c74g2000cwc.googlegroups.com> Sorry to bring it back up, but is there a way to spawn the process without Twisted? From brochu121 at gmail.com Mon Jun 5 19:21:29 2006 From: brochu121 at gmail.com (david brochu jr) Date: Mon, 5 Jun 2006 13:21:29 -0400 Subject: Starting New Process Message-ID: <9583ed900606051021xbcc2cceo6fefb0bdd134ed06@mail.gmail.com> try os.spawn() using the os module -------------- next part -------------- An HTML attachment was scrubbed... URL: 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 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 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 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 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 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 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 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 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 greg at cosc.canterbury.ac.nz Sat Jun 3 11:11:42 2006 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 03 Jun 2006 21:11:42 +1200 Subject: New to Python: Do we have the concept of Hash in Python? In-Reply-To: References: <1149182265.257263.159210@f6g2000cwb.googlegroups.com> Message-ID: <4ed222F1eao0mU2@individual.net> A.M wrote: > 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. Welcome aboard. It'll be interesting to see whether you *still* want to switch back to Ruby after getting to know Python for two years! -- Greg From greg.kujawa at gmail.com Fri Jun 2 23:50:13 2006 From: greg.kujawa at gmail.com (gregarican) Date: 2 Jun 2006 14:50:13 -0700 Subject: New to Python: Do we have the concept of Hash in Python? References: <1149182265.257263.159210@f6g2000cwb.googlegroups.com> Message-ID: <1149285013.705410.323330@j55g2000cwa.googlegroups.com> I needed certain Windows specific libraries that were difficult to impossible to do in Ruby. For example the Qt toolkit, LDAP support, and a WinCE implementation. Python is more Windows-friendly so I ported certain apps over to Python since Ruby left me hanging in just those specifics areas. As for my preferred language I use Smalltalk, Ruby, and Python each about a third of the time depending on what I'm looking to accomplish. For quick admin scripts Ruby is my choice, but perhaps that's just because I learned it first :-) Sion Arrowsmith wrote: > 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 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 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 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 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 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 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 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 bdesth.quelquechose at free.quelquepart.fr Sat Jun 3 02:09:17 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 03 Jun 2006 02:09:17 +0200 Subject: New to Python: Do we have the concept of Hash in Python? In-Reply-To: <_qOfg.1685$Su3.148290@news20.bellglobal.com> References: <1149206685.768210.71990@i39g2000cwa.googlegroups.com> <1149212030.851030.257180@c74g2000cwc.googlegroups.com> <_qOfg.1685$Su3.148290@news20.bellglobal.com> Message-ID: <4480a39f$0$20871$626a54ce@news.free.fr> A.M a ?crit : > Well the work is done now. I arrived home at 10:30 PM. > (snip) > > > 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.. But the better is yet to come !-) (FWIW, I use Python since the 1.5.2 days, and still learn new things almost everyday). > I had a productive day. Thanks > everybody for help. Welcome. 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 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 webraviteja at gmail.com Fri Jun 2 23:22:44 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 2 Jun 2006 14:22:44 -0700 Subject: New to Python: Do we have the concept of Hash in Python? In-Reply-To: <%aIfg.3027$EF1.232063@news20.bellglobal.com> References: <%aIfg.3027$EF1.232063@news20.bellglobal.com> Message-ID: <1149283364.026729.155370@h76g2000cwa.googlegroups.com> A.M wrote: > "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? IRC is a better place to request 10 key stroke answers. And it is faster for you to get answers there too. Usenet is archived these days and it adds value to all of us that it is filled with discussions of questions that are more intellectual than those which can be looked up at a glance at the documentation. From bdesth.quelquechose at free.quelquepart.fr Sat Jun 3 02:14:26 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 03 Jun 2006 02:14:26 +0200 Subject: New to Python: Do we have the concept of Hash in Python? In-Reply-To: References: <%aIfg.3027$EF1.232063@news20.bellglobal.com> Message-ID: <4480a4d5$0$20871$626a54ce@news.free.fr> Fredrik Lundh a ?crit : > "A.M" wrote: > > >>>are your boss aware of this ? >> >>In fact my boss is quite impressed with my progress so far. > > > *your* progress ? I think this meant "the progress status of the software". 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 runlevelten at gmail.com Thu Jun 29 10:58:42 2006 From: runlevelten at gmail.com (Ten) Date: Thu, 29 Jun 2006 09:58:42 +0100 Subject: New to Python: Do we have the concept of Hash in Python? In-Reply-To: References: Message-ID: <200606290958.42417.runlevelten@gmail.com> On Friday 02 June 2006 13:07, Piet van Oostrum wrote: > >>>>> "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 It's not that unfeasible - I can think of a few instances off the top of my head where management have read something in a magazine or heard something in conversation, then come in full of vim and vigour the next day - telling people to create item X using buzzword technology Y by the end of the day, the week or whatever, despite the devs having never seen it, despite the timescale being insufficient, and despite there being *real* work to do. Even if it's just because they want to see it, or to impress other management types with their use of the latest "trend", I believe the best response is to just get on with it. Self-preservation and all that. Even so, the idea of using python across the company is actually a very sensible one, so I expect it's programmer's enthusiasm fuelling things in this case. -- There are 10 types of people in this world, those who understand binary, and those who don't. From steve at holdenweb.com Thu Jun 29 14:36:37 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 29 Jun 2006 13:36:37 +0100 Subject: New to Python: Do we have the concept of Hash in Python? In-Reply-To: <200606290958.42417.runlevelten@gmail.com> References: <200606290958.42417.runlevelten@gmail.com> Message-ID: Ten wrote: > On Friday 02 June 2006 13:07, Piet van Oostrum wrote: > >>>>>>>"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 > > > It's not that unfeasible - I can think of a few instances off the top of my head where > management have read something in a magazine or heard something in conversation, then > come in full of vim and vigour the next day - telling people to create item X using buzzword > technology Y by the end of the day, the week or whatever, despite the devs having never seen it, > despite the timescale being insufficient, and despite there being *real* work to do. > [obYorkshireman] You were lucky. Mine used to come in like this *every bloody Monday morning*. British readers familiar with Kenneth Grahame's "The Wind in the Willows" will recognise a technological Mr. Toad here. The guy wanted to hit every available technology with a technical staff of two people, and seriously appeared to believe that he could just keep doing this until he came upon one that made money. Until it did he had the pleasure of bitching about how much of his money the company was swallowing. The last words I ever uttered to that man were a physiological impossibility. [Feels better]. > Even if it's just because they want to see it, or to impress other management types with their > use of the latest "trend", I believe the best response is to just get on with it. > Self-preservation and all that. > Clearly it's good press for Python if it *could* pass this test of usability. Don't see Perl users doing that (though, to be fair, I'm very little involved with Perl now). And since the boss signs the cheques, one should mollify them when ethically possible. > Even so, the idea of using python across the company is actually a very sensible one, so I expect > it's programmer's enthusiasm fuelling things in this case. > That's right, blame the poor technical staff ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From jzgoda at o2.usun.pl Fri Jun 2 23:32:57 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 02 Jun 2006 23:32:57 +0200 Subject: New to Python: Do we have the concept of Hash in Python? In-Reply-To: References: Message-ID: Fredrik Lundh napisa?(a): >>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... That's a great idea, anytime I had a problem with Java I would write c.l.j with heading "I am new to Java, but have solid background in Python, REXX and CL" and then I'll ask "do you have an implementation for tuple in Java?" or "how do I change an object generation routine for class?". At least, the are profis, they should know that. -- Jarek Zgoda http://jpa.berlios.de/ 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 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 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 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 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 fredrik at pythonware.com Sat Jun 3 10:42:27 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 03 Jun 2006 10:42:27 +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. I've posted a simple ImageQt interface module for PIL and PyQt4 here: http://svn.effbot.python-hosting.com/stuff/sandbox/pil/ImageQt.py this interface handles 1, P, L, and RGB images efficiently. usage: im = Image.open(...) # or some other pil operation qim = ImageQt.toimage(im) # to access the QImage, use qim.image. e.g: label.setPixmap(QtGui.QPixmap.fromImage(qim.image)) note that the toimage() function returns a wrapper object, not a QImage instance. I didn't find a reliable way to subclass from QImage, nor any other way to attach custom attributes to an existing QImage object. if anyone knows how to do that, let me know. From sreeram at tachyontech.net Sat Jun 3 14:35:14 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Sat, 03 Jun 2006 18:05:14 +0530 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: <44818202.8060607@tachyontech.net> Fredrik Lundh wrote: > Fredrik Lundh wrote: > > I've posted a simple ImageQt interface module for PIL and PyQt4 here: > > http://svn.effbot.python-hosting.com/stuff/sandbox/pil/ImageQt.py > I'm getting an 'unknown raw mode' error on ImageQt.py:59: data = im.tostring( "raw", "BGRX" ) Does this only work with PIL 1.1.6 snapshots? I currently have PIL 1.1.5. Regards Sreeram -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From fredrik at pythonware.com Sat Jun 3 15:19:55 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 03 Jun 2006 15:19:55 +0200 Subject: image lib & Qt4 In-Reply-To: <44818202.8060607@tachyontech.net> References: <1149173540.470829.34940@c74g2000cwc.googlegroups.com> <4e8haiF1dp2heU1@uni-berlin.de> <1149180814.585713.209640@i39g2000cwa.googlegroups.com> <44818202.8060607@tachyontech.net> Message-ID: K.S.Sreeram wrote: > I'm getting an 'unknown raw mode' error on ImageQt.py:59: > data = im.tostring( "raw", "BGRX" ) > > Does this only work with PIL 1.1.6 snapshots? I currently have > PIL 1.1.5. it was developed on Python 2.4.3 and PIL 1.1.5, so it should work. and BGRX support has been in there for ages (at least since 1.1.1). what happens if you do: $ python >>> import Image >>> im = Image.new("RGB", (100, 100)) >>> print len(im.tostring("raw", "BGRX")) 40000 From sreeram at tachyontech.net Sat Jun 3 15:41:57 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Sat, 03 Jun 2006 19:11:57 +0530 Subject: image lib & Qt4 In-Reply-To: References: <1149173540.470829.34940@c74g2000cwc.googlegroups.com> <4e8haiF1dp2heU1@uni-berlin.de> <1149180814.585713.209640@i39g2000cwa.googlegroups.com> <44818202.8060607@tachyontech.net> Message-ID: <448191A5.1050502@tachyontech.net> My bad. I was hacking the code trying to support RGBA mode images, and inadvertently i tried im.tostring("raw","BGRX") on the RGBA mode image. So BGRX does indeed work for RGB mode images. While trying to support RGBA mode images, i realized that a BGRA raw mode is needed for working with QImage. It doesn't seem to be supported by PIL. Any workarounds? Regards Sreeram Fredrik Lundh wrote: > $ python > >>> import Image > >>> im = Image.new("RGB", (100, 100)) > >>> print len(im.tostring("raw", "BGRX")) > 40000 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From fredrik at pythonware.com Sat Jun 3 16:13:04 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 03 Jun 2006 16:13:04 +0200 Subject: image lib & Qt4 In-Reply-To: <448191A5.1050502@tachyontech.net> References: <1149173540.470829.34940@c74g2000cwc.googlegroups.com> <4e8haiF1dp2heU1@uni-berlin.de> <1149180814.585713.209640@i39g2000cwa.googlegroups.com> <44818202.8060607@tachyontech.net> <448191A5.1050502@tachyontech.net> Message-ID: K.S.Sreeram wrote: > I was hacking the code trying to support RGBA mode images, and > inadvertently i tried im.tostring("raw","BGRX") on the RGBA mode image. > > So BGRX does indeed work for RGB mode images. > > While trying to support RGBA mode images, i realized that a BGRA raw > mode is needed for working with QImage. It doesn't seem to be supported > by PIL. Any workarounds? sure! here's a patch: Index: ImageQt.py =================================================================== --- ImageQt.py (revision 342) +++ ImageQt.py (working copy) @@ -58,6 +61,14 @@ elif im.mode == "RGB": data = im.tostring("raw", "BGRX") format = QImage.Format_RGB32 + elif im.mode == "RGBA": + try: + data = im.tostring("raw", "BGRA") + except SystemError: + # workaround for earlier versions + r, g, b, a = im.split() + im = Image.merge("RGBA", (b, g, r, a)) + format = QImage.Format_ARGB32 else: raise ValueError("unsupported image mode %r" % im.mode) From sreeram at tachyontech.net Sat Jun 3 16:21:35 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Sat, 03 Jun 2006 19:51:35 +0530 Subject: image lib & Qt4 In-Reply-To: References: <1149173540.470829.34940@c74g2000cwc.googlegroups.com> <4e8haiF1dp2heU1@uni-berlin.de> <1149180814.585713.209640@i39g2000cwa.googlegroups.com> <44818202.8060607@tachyontech.net> <448191A5.1050502@tachyontech.net> Message-ID: <44819AEF.6040609@tachyontech.net> thanks! so does that mean the BGRA raw mode is supported in PIL 1.1.6? Regards Sreeram Fredrik Lundh wrote: > K.S.Sreeram wrote: > >> I was hacking the code trying to support RGBA mode images, and >> inadvertently i tried im.tostring("raw","BGRX") on the RGBA mode image. >> >> So BGRX does indeed work for RGB mode images. >> >> While trying to support RGBA mode images, i realized that a BGRA raw >> mode is needed for working with QImage. It doesn't seem to be supported >> by PIL. Any workarounds? > > sure! here's a patch: > > Index: ImageQt.py > =================================================================== > --- ImageQt.py (revision 342) > +++ ImageQt.py (working copy) > @@ -58,6 +61,14 @@ > elif im.mode == "RGB": > data = im.tostring("raw", "BGRX") > format = QImage.Format_RGB32 > + elif im.mode == "RGBA": > + try: > + data = im.tostring("raw", "BGRA") > + except SystemError: > + # workaround for earlier versions > + r, g, b, a = im.split() > + im = Image.merge("RGBA", (b, g, r, a)) > + format = QImage.Format_ARGB32 > else: > raise ValueError("unsupported image mode %r" % im.mode) > > > -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From fredrik at pythonware.com Sat Jun 3 19:12:13 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 03 Jun 2006 19:12:13 +0200 Subject: image lib & Qt4 In-Reply-To: <44819AEF.6040609@tachyontech.net> References: <1149173540.470829.34940@c74g2000cwc.googlegroups.com> <4e8haiF1dp2heU1@uni-berlin.de> <1149180814.585713.209640@i39g2000cwa.googlegroups.com> <44818202.8060607@tachyontech.net> <448191A5.1050502@tachyontech.net> <44819AEF.6040609@tachyontech.net> Message-ID: K.S.Sreeram wrote: > so does that mean the BGRA raw mode is supported in PIL 1.1.6? possibly; I haven't checked. it does mean that some future version will most likely support it, at least. 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 steve at holdenweb.com Mon Jun 5 13:44:20 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 05 Jun 2006 12:44:20 +0100 Subject: An oddity in list comparison and element assignment In-Reply-To: <1149186735.650036.62670@i39g2000cwa.googlegroups.com> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> <127u81kdf70ch8d@corp.supernews.com> <1149186735.650036.62670@i39g2000cwa.googlegroups.com> Message-ID: <44841914.7080701@holdenweb.com> michael.f.ellis at gmail.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. > I suspect the word you are grasping for is "isomorphic", since your complaint appears to be that two non-isomorphic lists can compare as equal. He then later said: > 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. > So he designed it badly because he didn't anticipate its ubiquity? Give me a break. Every language designer regrets some of their decisions: it's almost a given for design of any kind, since one makes compromises without realising that they are compromises until usage reveals them. > Being a curmudgeon purist I'd actually prefer it if Python raised a > TypeError on float vs integer comparisons. > That's taking purity just a little too far for my taste. Looking at how this thread developed (if such an unedifying process can be described as "development") I hope you'll phrase future posts a little more carefully. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From michael.f.ellis at gmail.com Thu Jun 1 19:44:58 2006 From: michael.f.ellis at gmail.com (michael.f.ellis at gmail.com) Date: 1 Jun 2006 10:44:58 -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: <1149183898.338397.199070@y43g2000cwc.googlegroups.com> Hi Tim, In your example, a & b are references to the same object. I agree they should compare equally. But please note that a==b is True at every point in your example, even after the ValueError raised by b.remove(1). That's good consistent behavior. My original example is a little different. a and b never referred to the same object. They were containers created by different expressions with no object in common. The problem arises because the overloaded * operator makes row level copies of the lists in b. There's nothing wrong with that, but the fact remains that a and b are different in a very significant way. I agree with Alex that checking for this type of inequality is not a trivial programming exercise. It requires (at least) a parallel recursion that counts references with the containers being compared . At the same time, I know that much harder programming problems have been solved. Where I disagree with Alex is in the labeling of the existing behavior as 'natural'. Alternatively, it might make sense to disallow == for containers by raising a TypeError although that would eliminate a largely useful feature. Realistically, I know that Python is unlikely to adopt either alternative. It would probably break a lot of existing code. My point in the original post was to raise what I felt was a useful topic for discussion and to help others avoid a pitfall that cost me a couple of hours of head-scratching. By the way, I've been programming professionally for over 25 years and have used at least 30 different languages. During the past few years, Python has become my language of choice for almost everything because it helps me deliver more productivity and value to my clients. Cheers, Mike Tim Peters wrote: > 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. 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 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 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 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 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 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 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 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 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 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 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 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 hancock at anansispaceworks.com Fri Jun 2 21:21:47 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 02 Jun 2006 19:21:47 +0000 Subject: An oddity in list comparison and element assignment In-Reply-To: <1hg9nl6.xivwcd7n0j5N%aleax@mac.com> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> <1hg9nl6.xivwcd7n0j5N%aleax@mac.com> Message-ID: <44808FCB.1020206@anansispaceworks.com> Alex Martelli wrote: > 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 Not to detract from your point, but the "Heisenberg effect", if you mean the "Heisenberg uncertainty principle" is much more fundamental (and quantumly "spooky") than this. You are merely talking about the observer disturbing the system by the process of observation, which is a common problem, but has nothing to do with Heisenberg, and AFAIK, doesn't really have a name. It's a normal application of classical physics. I'm sorry to nitpick, it's just that it's one of those misconceptions that never wants to die, like thinking that gravity is caused by magnetism or the Earth's rotation, or that you can "get too close and be 'sucked in' by a strong gravity field", or that things are "weightless" in orbit, because they're "too far from the Earth's gravity". Cheers, Terry -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From michael.f.ellis at gmail.com Fri Jun 2 21:40:42 2006 From: michael.f.ellis at gmail.com (michael.f.ellis at gmail.com) Date: 2 Jun 2006 12:40:42 -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> <1hg9nl6.xivwcd7n0j5N%aleax@mac.com> Message-ID: <1149277242.199765.213600@g10g2000cwb.googlegroups.com> Perhaps a little background to my original post will defuse some of the controversy. While working during an airline flight, I ran into an unexpected outcome from using the * replication operator to initialize an array of lists. When I modified a single element of the array an entire column changed. Having no reference books or internet access available, I tried to understand what was going on by creating some small arrays on the command line to see if there was a difference between explicit initialization and initialization with range() and the * operator. The arrays looked identical when printed and a == b returned True. Yet the arrays were clearly not equivalent because mutating the corresponding elements produced different outcomes. I put the problem aside until the next day when I looked at it some more and and created the example script I posted. Just as I was about to hit the Send button, I realized that the * operator must have been creating references instead of copies. And then I appended the now much debated opinion that == should have detected the difference. (As an aside, may I point out that Python In A Nutshell states on page 46 "The result of S*n or n*S is the concatenation of n copies of S". It might be well to put a warning in a future edition that this is not strictly the case.) My viewpoint is that of a working professional software consultant. I'm essentially a pragmatist with no strong 'religious' views about languages and methodologies. As I noted in an earlier reply, I don't realistically expect Python to change the behavior of the == operator. I do think that a problem arose when it was adopted from C and extended to allow comparison of containers. In C, you can use it to compare integers, floats, and pointers and everyone understands that p==q does not imply *p == *q. Moreover, compilers issue warnings about comparisons between different types. Basically, I'm looking for simple diagnostic tools that make it easy to understand what's really going on when code produces an unexpected result. A 'strengthened equivalence' operator, to use your terminology would have been useful to me. As to constructing pseudocode for such an operator, I've appended a working script below. The counterexamples and questions from Slawomir, Maric, and Jim were really useful in sharpening my thinking about the matter. I'm sure there are many ways to break it. For example, tuples have no index method, so one would have to be written. Still, I hope it will serve to move the discussion beyond terms like 'crazy' and 'handwaving' and 'ill-founded'. I haven't used such perjoratives in any of my posts and would appreciate the same courtesy. Cheers, Mike ''' StrongEquality -- a first cut at the definition proposed by M. Ellis. Author: Michael F. Ellis, Ellis & Grant, Inc. ''' def indices(item,seq): '''Utility function that returns a list of indices where item occurs in seq''' result=[] for i in xrange(len(seq)): try: result.append(i+seq[i:].index(item)) except ValueError: return result def StrongEquality(a,b): '''True if a and b are numerically and "structurally" equal''' if a is b: return True if a != b: return False ## At this point we know a and b have the same length and ## evaluate numerically equivalent. We now need to figure out ## whether there are any references to identical objects in non-corresponding ## positions of a & b (per Slawomir's example). We also need to inspect ## a and b for non-matching patterns of identical references (per my example) ida=[] ; idb=[] for i in xrange(len(a)): if a[i] is b[i]: continue if isinstance(a[i], (int, float, str)) and isinstance(b[i], (int, float, str)): continue ## we already know they're numerically equal ida.append(id(a[i])) idb.append(id(b[i])) ## We know that ida[n] is not idb[n] for all n because we omitted all ## cases where a is b. Therefore Slawomir's example is detected if ## any id appears in both lists. for n in ida: if n in idb: return False ## Next we test for my example. I'm sure this can be coded more ## more elegantly ... for j in xrange(len(ida)): if indices(ida[j],ida) != indices(idb[j],idb): return False ## Lastly, recurse ... if not StrongEquality(a[i],b[i]): return False return True if __name__=='__main__': ## Rudimentary test cases assert StrongEquality(1,1) assert not StrongEquality(0,1) ## Slawomir's example x, y, z = [1],[1],[1] a, b = [x,y], [y,z] c, d = [[1],[1]], [[1],[1]] assert StrongEquality(c,d) assert a == b assert not StrongEquality(a,b) ## My example a =[[[1,2],[1,2]],[[1,2],[1,2]]] b = [[range(1,3)]*2]*2 assert a==b assert not StrongEquality(a,b) print "All tests ok." Alex Martelli wrote: > 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 tjreedy at udel.edu Sat Jun 3 03:56:22 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 2 Jun 2006 21:56:22 -0400 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><1hg9nl6.xivwcd7n0j5N%aleax@mac.com> <1149277242.199765.213600@g10g2000cwb.googlegroups.com> Message-ID: wrote in message news:1149277242.199765.213600 at g10g2000cwb.googlegroups.com... > (As an aside, may I point out that Python In A Nutshell states on page > 46 "The result of S*n or n*S is the concatenation of n copies of S". It would be more exact to say that S*n is [] extended with S n times, which makes it clear that 0*S == S*0 == [] and which avoids the apparently misleading word 'copy'. I presume the C implementation is the equivalent of def __mul__(inlist, times): result = [] for i in range(times): result.extend(inlist) return result Or one could say that the result *is the same as* (not *is*) the concatenation of n *shallow* copies of S. 'Shallow' means that each copy of S would have the same *content* (at the id level) as S, so that the result would contain the content of S n times, which is to say, when len(S) == 1, n slots with each slot bound to the *identical* content of S. When the content is immutable, the identicaliy does not matter. When it *is* mutable, it does. > It might be well to put a warning in a future edition that this is not > strictly the case.) Did you mean anything else by 'not strictly the case'? Terry Jan Reedy From aleax at mac.com Sat Jun 3 04:08:48 2006 From: aleax at mac.com (Alex Martelli) Date: Fri, 2 Jun 2006 19:08:48 -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> <1hg9nl6.xivwcd7n0j5N%aleax@mac.com> <1149277242.199765.213600@g10g2000cwb.googlegroups.com> Message-ID: <1hgbhhi.mcrge51cyj2isN%aleax@mac.com> wrote: ... > (As an aside, may I point out that Python In A Nutshell states on page > 46 "The result of S*n or n*S is the concatenation of n copies of S". It > might be well to put a warning in a future edition that this is not > strictly the case.) Can you give me an example where, say, for a sequence S, x = S * 3 is not structurally the same as x = copy.copy(S) + copy.copy(S) + copy.copy(S) ...? That is, where the "* 3" on a sequence is NOT the concatenation of three copies (ordinary copies, of course!) of that sequence? I don't think you can... and I can't repeatedly explain or point to the distinction between normal, ordinary, shallow copies on one side, and "deep copies" on the other, every single time in which that distinction MIGHT be relevant (because some reader might not be aware of it); such endless repetition would bloat the Nutshell totally away from its role as a CONCISE desktop reference, and seriously hamper its usefulness (particularly by DESTROYING any trace of usefulness for anybody who's finally *GOT* this crucial bit, but not just in that way). > languages and methodologies. As I noted in an earlier reply, I don't > realistically expect Python to change the behavior of the == operator. Then you might have avoided trying to convince anybody, or even trying to IMPLY, that in an ideal version of Python == *SHOULD* behave your way -- Python's semantics *ARE* entirely up for rediscussion at the moment, with an eye on the future "Python 3000" release, so this is one of the very rare periods of the history of the language where backwards incompatibility of a potential change is _NOT_ a blocking point. By asserting that your version of == would be "more natural", and trying to defend that assertion by vague handwaving references to maths and "real world", you managed to entirely shift MY mindstate (and possibly that of several other discussants) into one of total and absolute opposition to the proposal -- having by now spent considerable time and energy pondering and debating the issue, I am now entirely convinced that a language with such an == operator instead of Python's current one would be such a total, unadulterated disaster that I would refuse to use that language, no matter what other "good" features it might present to me. I've walked away from great jobs, just because they would have required me to use some technology I just could not stand, more than once already in my life: and this IS how strongly (and negatively) I feel about your claim that, for built-in ==, your semantics would be in any way preferable to Python's. By managing to thus focus my mindset (and make me spend my energy and time) in opposition to your claims of "more natural", you have at least managed to ensure that I will not now lend any scrap of help or support to your debugging needs. If you were as pragmatic as you claim to be, this kind of consideration WOULD have weighed highly in your choices. I.ie., if you had WANTED to attract any such support and help, a completely different attitude than that "most natural" claim would have been ENORMOUSLY more productive -- and your continuing attempts to debate that issue aren't helping AT ALL either: > I do think that a problem arose when it was adopted from C and extended > to allow comparison of containers. In C, you can use it to compare > integers, floats, and pointers and everyone understands that p==q does > not imply *p == *q. If that is so, then everyone is utterly, totally, entirely, horribly *WRONG*, because, in C, p==q ***DOES*** imply *p == *q (whenever p -- and by consequence q, given equality -- may legitimately be dereferenced: p == q == 0 does not imply anything about *p and/or *q, which may produce random results, crash the process, or whatever -- of course). You no doubt meant to say something entirely different from what you ACTUALLY said, but I respectfully suggest you spare your breath rather than keep trying to defend an indefensible position. I do NOT agree, and I cannot imagine any state of the world that would get me to agree, with your claim that "a problem arose" by allowing equality comparison of containers in Python (many other languages allow such comparisons, BTW; I would consider it a horrible wart if a language claiming to be "higher level" did NOT). That you're "supporting" (HA!) your absurd claim with an equally absurd (and obviously, wholly false, unfounded, and misplaced) claim about C pointers doesn't "help", of course, but even perfectly accurate claims about C (or machine code, or Cobol, or RPG...) would be pretty much uninteresting and irrelevant. > Moreover, compilers issue warnings about > comparisons between different types. Some do, some don't, depending on the case -- e.g., I do not believe that even with -Wall (or the equivalent setting) any C compiler whines about EQUALITY comparisons of signed and unsigned integers (as well they shouldn't, of course)! And, just as of course, this umpteenth side-path you're introducing has really nothing to do with the case, since when you're comparing two lists-containing-lists which are equal by Python's rules but according to your original claims about what's "more natural" ``should not'' be, you ARE anyway comparing object of equal types. > Basically, I'm looking for simple diagnostic tools that make it easy to > understand what's really going on when code produces an unexpected > result. A 'strengthened equivalence' operator, to use your terminology > would have been useful to me. A *FUNCTION* performing such checks in a debugging and diagnostics package would have been -- and if you hadn't pushed me to spend so much time and energy defending Python's design choices against your claims that other choices would be "more natural", you might have gotten help and support in developing it. But you chose to make ill-founded claims of "more natural", and therefore you got a flamewar instead: your choice. > will serve to move the discussion beyond terms like 'crazy' and > 'handwaving' and 'ill-founded'. I haven't used such perjoratives in > any of my posts and would appreciate the same courtesy. You claimed that Python's semantics are "contrary to one of my fundamental expectations", "an oddity", resulting only (you said in your second post) from a "performance and memory optimization", and tried to justify this severe criticism of Python by vague (i..e, "handwaving") appeals to analogies with "maths" and "the real world". I do not believe that such scathing criticism had any sound foundations, nor that calling it "ill-founded" is anything but a fittingly accurate description: and a language where the == operator DID satisfy the constraints you claimed to desire for *THE EQUALITY OPERATOR ITSELF* (as opposed to, for some helper/checker function in a separate module for checking and debugging) would be a crazy one indeed. If my opinions that, I believe, accurately reflect the facts of the case, sound "pejorative" to you, well, that's not a matter of choice of words on my part, as much as of your choice of what to express in the first place. Take your recent claim that in C "everyone understands that p==q does not imply *p == *q"; which of the many ("pejorative") adjectives I tagged your assertion with do you think are inaccurate or inappropriate? I called it wrong, absurd, false, unfounded, and misplaced, and seasoned the mix with a choice of adverbs including "utterly" and "horribly". It appears to me that each of these adjectives and adverbs is appropriate and accurate (though it's repetitious on my part to use them all, that repetition does convey the intensity of my opinions in the matter). This is a factual issue where it's easy to defend strongly held opinions (which may be checked against "facts"); in matters of "should" (what semantics "should" a certain language construct HAVE, in order to be most natural, simplest, and most useful -- quite apart from any issues of optimization) such ease is, alas, not given... but the fact that veryfying clashing opinons about what "should" be the case is way harder than opinions easily checkable against "facts", does not mean that the "should"'s (which are even more important, potentially, in their effect on future language design!) are any less important -- on the contrary. I do not believe I am going to follow this thread any more; I wish you best of luck in your future endeavors -- and, if you can get back to being the pragmatist that you claim to be, perhaps in the future you may chose to express your debugging needs and desiderata in ways that dispose the experts on some give technology to help and support you, rather than to fight against the damage which, they opine, it would cause to the future of that technology if certain ("crazy") suggestions were to be part of it. Alex From anton.vredegoor at gmail.com Sat Jun 3 07:36:37 2006 From: anton.vredegoor at gmail.com (anton.vredegoor at gmail.com) Date: Sat, 03 Jun 2006 07:36:37 +0200 Subject: An oddity in list comparison and element assignment In-Reply-To: <1hgbhhi.mcrge51cyj2isN%aleax@mac.com> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> <1hg9nl6.xivwcd7n0j5N%aleax@mac.com> <1149277242.199765.213600@g10g2000cwb.googlegroups.com> <1hgbhhi.mcrge51cyj2isN%aleax@mac.com> Message-ID: Alex Martelli wrote: [snip] Can somebody please shut down this bot? I think it's running out of control. It seems to be unable to understand that "don't be evil" might be good when you're small (at least it's not very bad) but that it becomes distinctly evil when you're big. What is good when you're big? I really don't know and I think there's even not many other people who do. But simply forbidding things that are not precisely definable -the way mathematicians have been doing before physicists shook them out of it- seems to do more harm than good. In my opinion it looks like there is a path from rigid rule adherence to slowly accepting more doubt and inconsistencies -because we're all adults here- and this has something to do with letting go of things like childish adherence to static typing and confusion between equality and identity. Let me qualify that last paragraph before anyone concludes I have become disfunctional too and will lead everyone to their destruction. There seem to always be certain unclear parts in a programming language and people are constantly trying out new structures in order to map some new territory. I remember sets, generators and metaclasses. Only after people noticing problems (don't modify the thing you're iterating over) ways are found to solve them (you can if you put everything back just at the right moment) and finally these ways are condensed into officially endorsed coding practices. Now we're struggling with immutability and sequences. They're not a problem if you know what you're doing, but what exactly is it that those who know what they're doing do? It indicates that maybe it's the birth of a new language construct. But why should it stop there? I expect a certain openness and willingness to discuss controversial matters from a community even if it were only to educate newcomers. But it might be the case that such willingness to accept doubt, without it turning into actively seeking it -that seems to be foolish, but who am I to judge even that- is what makes it possible to develop higher language and cognitive structures. Anton 'even if it means turning into lisp before moving on' From aleax at mac.com Sat Jun 3 08:11:37 2006 From: aleax at mac.com (Alex Martelli) Date: Fri, 2 Jun 2006 23:11:37 -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> <1hg9nl6.xivwcd7n0j5N%aleax@mac.com> <1149277242.199765.213600@g10g2000cwb.googlegroups.com> <1hgbhhi.mcrge51cyj2isN%aleax@mac.com> Message-ID: <1hgbu61.1gtkkjh1aca3i8N%aleax@mac.com> wrote: > Alex Martelli wrote: > > [snip] > > Can somebody please shut down this bot? I think it's running out of Much as you might love for somebody to "shut me down", that (unfortunately, no doubt, from your viewpoint) is quite unlikely to happen. Although "making predictions is always difficult, especially about the future", the most likely course of events is that I shall continue for a while to survive, probably in tolerable health. BTW, and for your information: in modern Western society, publically wishing for some adversary's death is often considered somewhat uncouth and rude, except perhaps in times of war or similar extremities. Being aware of such social niceties and conventions may help: even were I to wish that somebody crushed you underfoot like the worm you are, I would avoid expressing such a wish in public, and likely in private too. Alex From anton.vredegoor at gmail.com Sat Jun 3 09:06:39 2006 From: anton.vredegoor at gmail.com (anton.vredegoor at gmail.com) Date: Sat, 03 Jun 2006 09:06:39 +0200 Subject: An oddity in list comparison and element assignment In-Reply-To: <1hgbu61.1gtkkjh1aca3i8N%aleax@mac.com> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> <1hg9nl6.xivwcd7n0j5N%aleax@mac.com> <1149277242.199765.213600@g10g2000cwb.googlegroups.com> <1hgbhhi.mcrge51cyj2isN%aleax@mac.com> <1hgbu61.1gtkkjh1aca3i8N%aleax@mac.com> Message-ID: Alex Martelli wrote: > wrote: >> Can somebody please shut down this bot? I think it's running out of > > Much as you might love for somebody to "shut me down", that > (unfortunately, no doubt, from your viewpoint) is quite unlikely to > happen. Although "making predictions is always difficult, especially > about the future", the most likely course of events is that I shall > continue for a while to survive, probably in tolerable health. You've got that completely wrong. I was not trying to kill you but I was trying to revive you. A process that is not evolving is dead. Stopping it frees up valuable resources that enable it to become alive again. Anton 'being alive is being mutable' From michael.f.ellis at gmail.com Sat Jun 3 14:24:35 2006 From: michael.f.ellis at gmail.com (michael.f.ellis at gmail.com) Date: 3 Jun 2006 05:24:35 -0700 Subject: An oddity in list comparison and element assignment In-Reply-To: <1hgbhhi.mcrge51cyj2isN%aleax@mac.com> References: <1149174141.395647.48940@u72g2000cwu.googlegroups.com> <1hg8ug8.m01zhwehpk66N%aleax@mac.com> <1149177617.985251.74560@c74g2000cwc.googlegroups.com> <1hg9nl6.xivwcd7n0j5N%aleax@mac.com> <1149277242.199765.213600@g10g2000cwb.googlegroups.com> <1hgbhhi.mcrge51cyj2isN%aleax@mac.com> Message-ID: <1149337475.944457.168300@y43g2000cwc.googlegroups.com> Hey Alex, lighten up! Python is a programming language -- not your family, religion, or civil rights. Cheers, Mike Alex Martelli wrote: > wrote: > ... > > (As an aside, may I point out that Python In A Nutshell states on page > > 46 "The result of S*n or n*S is the concatenation of n copies of S". It > > might be well to put a warning in a future edition that this is not > > strictly the case.) > > Can you give me an example where, say, for a sequence S, > > x = S * 3 > > is not structurally the same as > > x = copy.copy(S) + copy.copy(S) + copy.copy(S) > > ...? That is, where the "* 3" on a sequence is NOT the concatenation of > three copies (ordinary copies, of course!) of that sequence? I don't > think you can... and I can't repeatedly explain or point to the > distinction between normal, ordinary, shallow copies on one side, and > "deep copies" on the other, every single time in which that distinction > MIGHT be relevant (because some reader might not be aware of it); such > endless repetition would bloat the Nutshell totally away from its role > as a CONCISE desktop reference, and seriously hamper its usefulness > (particularly by DESTROYING any trace of usefulness for anybody who's > finally *GOT* this crucial bit, but not just in that way). > > > > languages and methodologies. As I noted in an earlier reply, I don't > > realistically expect Python to change the behavior of the == operator. > > Then you might have avoided trying to convince anybody, or even trying > to IMPLY, that in an ideal version of Python == *SHOULD* behave your way > -- Python's semantics *ARE* entirely up for rediscussion at the moment, > with an eye on the future "Python 3000" release, so this is one of the > very rare periods of the history of the language where backwards > incompatibility of a potential change is _NOT_ a blocking point. > > By asserting that your version of == would be "more natural", and trying > to defend that assertion by vague handwaving references to maths and > "real world", you managed to entirely shift MY mindstate (and possibly > that of several other discussants) into one of total and absolute > opposition to the proposal -- having by now spent considerable time and > energy pondering and debating the issue, I am now entirely convinced > that a language with such an == operator instead of Python's current one > would be such a total, unadulterated disaster that I would refuse to use > that language, no matter what other "good" features it might present to > me. I've walked away from great jobs, just because they would have > required me to use some technology I just could not stand, more than > once already in my life: and this IS how strongly (and negatively) I > feel about your claim that, for built-in ==, your semantics would be in > any way preferable to Python's. > > By managing to thus focus my mindset (and make me spend my energy and > time) in opposition to your claims of "more natural", you have at least > managed to ensure that I will not now lend any scrap of help or support > to your debugging needs. If you were as pragmatic as you claim to be, > this kind of consideration WOULD have weighed highly in your choices. > > I.ie., if you had WANTED to attract any such support and help, a > completely different attitude than that "most natural" claim would have > been ENORMOUSLY more productive -- and your continuing attempts to > debate that issue aren't helping AT ALL either: > > > I do think that a problem arose when it was adopted from C and extended > > to allow comparison of containers. In C, you can use it to compare > > integers, floats, and pointers and everyone understands that p==q does > > not imply *p == *q. > > If that is so, then everyone is utterly, totally, entirely, horribly > *WRONG*, because, in C, p==q ***DOES*** imply *p == *q (whenever p -- > and by consequence q, given equality -- may legitimately be > dereferenced: p == q == 0 does not imply anything about *p and/or *q, > which may produce random results, crash the process, or whatever -- of > course). > > You no doubt meant to say something entirely different from what you > ACTUALLY said, but I respectfully suggest you spare your breath rather > than keep trying to defend an indefensible position. > > I do NOT agree, and I cannot imagine any state of the world that would > get me to agree, with your claim that "a problem arose" by allowing > equality comparison of containers in Python (many other languages allow > such comparisons, BTW; I would consider it a horrible wart if a language > claiming to be "higher level" did NOT). That you're "supporting" (HA!) > your absurd claim with an equally absurd (and obviously, wholly false, > unfounded, and misplaced) claim about C pointers doesn't "help", of > course, but even perfectly accurate claims about C (or machine code, or > Cobol, or RPG...) would be pretty much uninteresting and irrelevant. > > > Moreover, compilers issue warnings about > > comparisons between different types. > > Some do, some don't, depending on the case -- e.g., I do not believe > that even with -Wall (or the equivalent setting) any C compiler whines > about EQUALITY comparisons of signed and unsigned integers (as well they > shouldn't, of course)! > > And, just as of course, this umpteenth side-path you're introducing has > really nothing to do with the case, since when you're comparing two > lists-containing-lists which are equal by Python's rules but according > to your original claims about what's "more natural" ``should not'' be, > you ARE anyway comparing object of equal types. > > > Basically, I'm looking for simple diagnostic tools that make it easy to > > understand what's really going on when code produces an unexpected > > result. A 'strengthened equivalence' operator, to use your terminology > > would have been useful to me. > > A *FUNCTION* performing such checks in a debugging and diagnostics > package would have been -- and if you hadn't pushed me to spend so much > time and energy defending Python's design choices against your claims > that other choices would be "more natural", you might have gotten help > and support in developing it. But you chose to make ill-founded claims > of "more natural", and therefore you got a flamewar instead: your > choice. > > > will serve to move the discussion beyond terms like 'crazy' and > > 'handwaving' and 'ill-founded'. I haven't used such perjoratives in > > any of my posts and would appreciate the same courtesy. > > You claimed that Python's semantics are "contrary to one of my > fundamental expectations", "an oddity", resulting only (you said in your > second post) from a "performance and memory optimization", and tried to > justify this severe criticism of Python by vague (i..e, "handwaving") > appeals to analogies with "maths" and "the real world". > > I do not believe that such scathing criticism had any sound foundations, > nor that calling it "ill-founded" is anything but a fittingly accurate > description: and a language where the == operator DID satisfy the > constraints you claimed to desire for *THE EQUALITY OPERATOR ITSELF* (as > opposed to, for some helper/checker function in a separate module for > checking and debugging) would be a crazy one indeed. If my opinions > that, I believe, accurately reflect the facts of the case, sound > "pejorative" to you, well, that's not a matter of choice of words on my > part, as much as of your choice of what to express in the first place. > > Take your recent claim that in C "everyone understands that p==q does > not imply *p == *q"; which of the many ("pejorative") adjectives I > tagged your assertion with do you think are inaccurate or inappropriate? > I called it wrong, absurd, false, unfounded, and misplaced, and seasoned > the mix with a choice of adverbs including "utterly" and "horribly". It > appears to me that each of these adjectives and adverbs is appropriate > and accurate (though it's repetitious on my part to use them all, that > repetition does convey the intensity of my opinions in the matter). > > This is a factual issue where it's easy to defend strongly held opinions > (which may be checked against "facts"); in matters of "should" (what > semantics "should" a certain language construct HAVE, in order to be > most natural, simplest, and most useful -- quite apart from any issues > of optimization) such ease is, alas, not given... but the fact that > veryfying clashing opinons about what "should" be the case is way harder > than opinions easily checkable against "facts", does not mean that the > "should"'s (which are even more important, potentially, in their effect > on future language design!) are any less important -- on the contrary. > > > I do not believe I am going to follow this thread any more; I wish you > best of luck in your future endeavors -- and, if you can get back to > being the pragmatist that you claim to be, perhaps in the future you may > chose to express your debugging needs and desiderata in ways that > dispose the experts on some give technology to help and support you, > rather than to fight against the damage which, they opine, it would > cause to the future of that technology if certain ("crazy") suggestions > were to be part of it. > > > Alex From aleax at mac.com Sat Jun 3 04:25:44 2006 From: aleax at mac.com (Alex Martelli) Date: Fri, 2 Jun 2006 19:25:44 -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> <1hg9nl6.xivwcd7n0j5N%aleax@mac.com> <1149277242.199765.213600@g10g2000cwb.googlegroups.com> Message-ID: <1hgbjx1.1gn7haipx7x5N%aleax@mac.com> Terry Reedy wrote: > wrote in message > news:1149277242.199765.213600 at g10g2000cwb.googlegroups.com... > > (As an aside, may I point out that Python In A Nutshell states on page > > 46 "The result of S*n or n*S is the concatenation of n copies of S". > > It would be more exact to say that S*n is [] extended with S n times, > which makes it clear that 0*S == S*0 == [] and which avoids the apparently > misleading word 'copy'. I presume the C implementation is the equivalent Considering that the very next (and final) sentence in that same paragraph is "If n is zero or less than zero, the result is an empty sequence of the same type as S", I don't think there's anything misleading in the quoted sentence. Moreover, since the paragraph is about sequences, not just lists, it *WOULD* be horribly wrong to use the phrasing you suggest: "bah!"*3 is NOT a list, it's EXACTLY the concatenation of three copies of that string -- no more, no less. > Or one could say that the result *is the same as* (not *is*) the I find this distinction, in this context, to be empty padding, with zero added value on ANY plane -- including the plane of "pedantry";-). > concatenation of n *shallow* copies of S. 'Shallow' means that each copy I do not think it would be good to introduce the concept of "shallow" at a point in the text which is talking about ALL sequences -- including ones, such as strings, for which it just does not apply. But, thanks for the suggestions, anyway! Alex From tjreedy at udel.edu Sun Jun 4 01:25:26 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 3 Jun 2006 19:25:26 -0400 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><1hg9nl6.xivwcd7n0j5N%aleax@mac.com><1149277242.199765.213600@g10g2000cwb.googlegroups.com> <1hgbjx1.1gn7haipx7x5N%aleax@mac.com> Message-ID: "Alex Martelli" wrote in message news:1hgbjx1.1gn7haipx7x5N%aleax at mac.com... > Terry Reedy wrote: > >> wrote in message >> news:1149277242.199765.213600 at g10g2000cwb.googlegroups.com... >> > (As an aside, may I point out that Python In A Nutshell states on page >> > 46 "The result of S*n or n*S is the concatenation of n copies of S". Alex, in responding to this sentence lifted out of context by Michael, I am responding more to him and his claim of 'not strictly the case' than to you. What I wrote is also more a draft of a paragraph for a book of mine (of no competition to yours) than a suggestion for a future edition of your book. >> It would be more exact to say that S*n is [] extended with S n times, A**b is often explained as 'A multiplied by itself b times' or some such. It is more exact to say it is '1 multiplied by A b times' >> which makes it clear that 0*S == S*0 == [] which makes it clear that A**0, including 0**0, is 1. >> and which avoids the apparently misleading word 'copy'. Given the number of people, including Michael, who have posted puzzlement based on their confusion as to what does and does not get copied, I don't think it unfair to call 'copy' 'apparently misleading. My intention in this phrase is to suggest that one who misunderstands 'copy' in this context will be mislead while one who understands just what is copied and what is not copied will not. The point of my code snippet was to explain/illustrate what is copied. While it will (obviously) only executive as Python code for lists, I believe the algorithm is generic if the initial assignment and list.extend method are suitably interpreted. Of course, I presume that in the CPython code, the actual initialization is more like (length one blank value) * (n*len(S)) followed by n slice assignments, but the Python code for this would still be list specific and would also be more complex, without much aiding comprehension of the result. Strings are a somewhat special case since the characters in the string are not wrapped as Python objects unless and until extracted from the string. So one cannot as easily talk about the object(s) contained in the sequence. > Considering that the very next (and final) sentence in that same > paragraph is "If n is zero or less than zero, the result is an empty > sequence of the same type as S", I don't think there's anything > misleading in the quoted sentence. In its original context, with respect to that issue, no. But as I said, I was responding to Michael's removed-from-context quotation and his claim about the need for a warning. I wonder if you read down to the end, where I asked him whether I had missed anything he might find fault with, before you responded. > Moreover, since the paragraph is about sequences, not just lists, This *thread* is about repetition of lists, and in particular, a list of one (or more) lists, and the consequences of the mutability of the inner lists, and that is the context in which I wrote. > it *WOULD* be horribly wrong to use the phrasing you suggest: In a generic context, [] would obviously have to be replaced by 'null sequence of the type of S', which in many cases is type(S)(). And 'extend' would have to be interpreted generically, as something the interpreter would do behind the scenes in type(S). __new__, although as I said before, I don't think that is exactly what it does do. >"bah!"*3 is NOT a list, Duh., > it's EXACTLY the > concatenation of three copies of that string -- no more, no less. Depends what one means by 'copy'. See below for your alternate wording. >> Or one could say that the result *is the same as* (not *is*) the > > I find this distinction, in this context, to be empty padding, with zero > added value on ANY plane -- including the plane of "pedantry";-). Perhaps you should tone down the overwrought emotionalism and take a look in a mirror. In *your* response to Michael you made the *same* distinction: >> Can you give me an example where, say, for a sequence S, >> x = S * 3 >> is not structurally the same as >> x = copy.copy(S) + copy.copy(S) + copy.copy(S) I agree that adding 'structurally' makes the 'padding' even better. >> concatenation of n *shallow* copies of S. 'Shallow' means that each >> copy > I do not think it would be good to introduce the concept of "shallow" at > a point in the text which is talking about ALL sequences -- including > ones, such as strings, for which it just does not apply. Again, I was not suggesting that you do so. Adding 'shallow' was intentially pedantic for Michael's 'benefit'. To be clear, I was *NOT* supporting his warning suggestion. > But, thanks for the suggestions, anyway! We both have the goal of expaining Python better so beginners hit fewer bumps on the road. Terry Jan Reedy From aleax at mac.com Sun Jun 4 02:03:00 2006 From: aleax at mac.com (Alex Martelli) Date: Sat, 3 Jun 2006 17:03:00 -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> <1hg9nl6.xivwcd7n0j5N%aleax@mac.com> <1149277242.199765.213600@g10g2000cwb.googlegroups.com> <1hgbjx1.1gn7haipx7x5N%aleax@mac.com> Message-ID: <1hgd7ry.1lrs9rqnn77ayN%aleax@mac.com> Terry Reedy wrote: > > it's EXACTLY the > > concatenation of three copies of that string -- no more, no less. > > Depends what one means by 'copy'. See below for your alternate wording. Please give me a reasonable definition of the unadorned word "copy" which would make this statement false. (And, just to forestall one possible attempt: no, I cannot agree that a ``deepcopy'' is a reasonable definition of the _unadorned_ word "copy"). > >> Or one could say that the result *is the same as* (not *is*) the > > > > I find this distinction, in this context, to be empty padding, with zero > > added value on ANY plane -- including the plane of "pedantry";-). > > Perhaps you should tone down the overwrought emotionalism and take a look > in a mirror. In *your* response to Michael you made the *same* > distinction: I did not *DRAW* any distinction (as you did with your parenthetical note "(not *is*)", emphasis and all) -- rather, I used one of many reasonably interchangeable ways to word a concept. ((In the Nutshell, I always deliberately try to pick the shortest and most concise way; in my more spontaneous writing, I strongly tend to wilder exhuberance). So, having deeply delved into the mirror, I still fail to find any validity in your criticism: the phrases "S*n is the same as the concatenation of" and "S*n the concatenation of", taken as definitions of what S*n means, are such that your emphatic distinction has no added value whatsoever -- I stand by this assertion and fail to see in it any emotionalism, overwrought or otherwise. Care to _defend_ your criticism, with some _objective_ explanation of why that parenthetical was warranted (particularly the emphasis within it)? Or would you rather continue the personal attacks against me and the unproven accusations of "overwrought emotionalism" in particular? Alex From slawomir.nowaczyk.847 at student.lu.se Mon Jun 5 11:48:05 2006 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Mon, 05 Jun 2006 11:48:05 +0200 Subject: An oddity in list comparison and element assignment In-Reply-To: <1hgd7ry.1lrs9rqnn77ayN%aleax@mac.com> References: <1hgd7ry.1lrs9rqnn77ayN%aleax@mac.com> Message-ID: <20060605114741.FC69.SLAWOMIR.NOWACZYK.847@student.lu.se> On Sat, 03 Jun 2006 17:03:00 -0700 aleax at mac.com (Alex Martelli) wrote: #> Terry Reedy wrote: #> #> > Depends what one means by 'copy'. See below for your alternate wording. #> #> Please give me a reasonable definition of the unadorned word "copy" #> which would make this statement false. (And, just to forestall one #> possible attempt: no, I cannot agree that a ``deepcopy'' is a reasonable #> definition of the _unadorned_ word "copy"). Actually, when *I* think about the word "copy", I have in mind what happens with files... and I to me semantics of []*3 is more like symbolic linking, not copying. While I, personally, understand the sentence in question "The result of S*n or n*S is the concatenation of n copies of S" correctly, I *do* see how it might be misunderstood by others. Not that I know how to express it better :-( -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) Don't wake me for the end of the world unless it has very good special effects -- Roger Zelazny From aleax at mac.com Mon Jun 5 16:24:57 2006 From: aleax at mac.com (Alex Martelli) Date: Mon, 5 Jun 2006 07:24:57 -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> <1hg9nl6.xivwcd7n0j5N%aleax@mac.com> <1149277242.199765.213600@g10g2000cwb.googlegroups.com> <1hgbjx1.1gn7haipx7x5N%aleax@mac.com> <1hgd7ry.1lrs9rqnn77ayN%aleax@mac.com> Message-ID: <1hgg5o4.rfx6dk1tmcn6rN%aleax@mac.com> Slawomir Nowaczyk wrote: > On Sat, 03 Jun 2006 17:03:00 -0700 > aleax at mac.com (Alex Martelli) wrote: > > #> Terry Reedy wrote: > #> > #> > Depends what one means by 'copy'. See below for your alternate wording. > #> > #> Please give me a reasonable definition of the unadorned word "copy" > #> which would make this statement false. (And, just to forestall one > #> possible attempt: no, I cannot agree that a ``deepcopy'' is a reasonable > #> definition of the _unadorned_ word "copy"). > > Actually, when *I* think about the word "copy", I have in mind what > happens with files... Sure! In particular, to reproduce the concept of an object containing references to other objects, imagine that the file is a .tar, .dmg (on MacOSX), or other kind of "container"/"archive" kind of file, and one of the items in its contents is a symbolic link. When you copy the archive file, both the original and the copy now contain symbolic links to the SAME target. > and I to me semantics of []*3 is more like > symbolic linking, not copying. ??? an _assignment_ in Python can be said to be "like symbolic linking, not copying" -- and that's a crucial part of Python's semantics, of course. But the Sequence*N operation has nothing to do with creating symbolic links; it may (of course) _copy_ such links, if they're present in the sequence, just like copying a container file copies symbolic links it may contain -- in each case one can end up with symbolic links to the same target. The analogy between files and Python objects is of course not exact (partly because filesystems normally distinguish between directories, which only contain references to files, and "ordinary" files, that don't -- the Composite Design Pattern proceeds, often fruitfully, by abstracting away this distinction), but in as far as it holds, it points roughly in the right direction. (GNU's cp offers a -R switch to explicitly perform a "recursive copy", with other switches such as -H, -L, -P to affect what happens in that case to symlinks -- this -R is more akin to "deep copying", except that Python's deepcopy is simpler, and always "recurses to the hilt"). > While I, personally, understand the > sentence in question "The result of S*n or n*S is the concatenation of > n copies of S" correctly, I *do* see how it might be misunderstood by > others. > > Not that I know how to express it better :-( I do find it interesting that the concept of "copy" causes such trouble, even when the analogies used (filecopying and symlinks) would tend to point in the right direction. The "real-life" analogy of copying a list also points in the right direction: if I have a list of the writings I hold on my library's top shelf, when I copy the list, both the original and the copy point to _exactly the same_ writings -- not to separate copies of each. If I asked an employee to "please copy this list" I would be astonished if he or she by default also copied each other writing that is an _item_ on the list -- surely I would expect such huge amounts of work to happen only when explicitly requested, and the default meaning of "copy" to be therefore ``shallow'' (wherever applicable, that is, when copying something that references other things). It would be interesting to study the root of the confusion in more detail (although it's unlikely, as you indicate, that such study would yield a different definition, concise and simple enough to be used in a concise reference work, it would still help authors of tutorials). Alex 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 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 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 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 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 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 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 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 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 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 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 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 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 jcb at iteris.com Thu Jun 1 20:03:01 2006 From: jcb at iteris.com (Metalone) Date: 1 Jun 2006 11:03:01 -0700 Subject: Python for Visual Basic or C# programmers References: Message-ID: <1149184981.184143.63160@f6g2000cwb.googlegroups.com> A.M wrote: > 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 > > Alan Python has a str() function that is close to vb's str. The Python version does not produce a leading space. str(123) --> '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 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 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 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 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 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 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 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 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 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 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 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 aisaac0 at verizon.net Sun Jun 4 01:45:31 2006 From: aisaac0 at verizon.net (David Isaac) Date: Sat, 03 Jun 2006 23:45:31 GMT Subject: numpy bug References: <447f3338$1_7@news.bluewin.ch> Message-ID: "Boris Borcic" wrote in message news:447f3338$1_7 at 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 Most bug reports start on the numpy list, I believe. (See above.) Cheers, Alan Isaac 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 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 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 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 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 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 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 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 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 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 tjreedy at udel.edu Fri Jun 2 21:15:37 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 2 Jun 2006 15:15:37 -0400 Subject: win32com: how to connect to a specific instance of a runningobject? References: <1149254270.790703.145700@j55g2000cwa.googlegroups.com><1149260253.337452.65770@c74g2000cwc.googlegroups.com> <1149273628.486179.224680@h76g2000cwa.googlegroups.com> Message-ID: "ago" wrote in message news:1149273628.486179.224680 at 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 Perhaps you can submit this to the Python Cookbook at oreilly.com (sp?) 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 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 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 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 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 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 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 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 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 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 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 bdesth.quelquechose at free.quelquepart.fr Sat Jun 3 01:58:33 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 03 Jun 2006 01:58:33 +0200 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: <4480a11b$0$6172$626a54ce@news.free.fr> nicolasg at gmail.com a ?crit : > 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. Could you explain the difference ? From bdesth.quelquechose at free.quelquepart.fr Sat Jun 3 01:56:03 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 03 Jun 2006 01:56:03 +0200 Subject: integer to binary... In-Reply-To: <127ugf9jgu7av18@corp.supernews.com> References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> <127ugf9jgu7av18@corp.supernews.com> Message-ID: <4480a084$0$6172$626a54ce@news.free.fr> Grant Edwards a ?crit : > 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. Not really. >>> (7).__class__ >>> dir((7)) ['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__str__', '__sub__', '__truediv__', '__xor__'] >>> From grante at visi.com Sat Jun 3 17:06:16 2006 From: grante at visi.com (Grant Edwards) Date: Sat, 03 Jun 2006 15:06:16 -0000 Subject: integer to binary... References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> <127ugf9jgu7av18@corp.supernews.com> <4480a084$0$6172$626a54ce@news.free.fr> Message-ID: <12839b8doin7mff@corp.supernews.com> On 2006-06-02, Bruno Desthuilliers wrote: > Grant Edwards a ?crit : >> 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. > > Not really. Yes, really. Otherwise the bitwise boolean operations you demonstrated wouldn't work as shown. >>>> (7).__class__ > >>>> dir((7)) > ['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', > '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', > '__floordiv__', '__getattribute__', '__getnewargs__', '__hash__', > '__hex__', '__init__', '__int__', '__invert__', '__long__', > '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', > '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', > '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', > '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', > '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', > '__rxor__', '__setattr__', '__str__', '__sub__', '__truediv__', '__xor__'] >>>> The fact that they impliment the xor operator is pretty much proof that integers are stored in binary format -- xor is only defined for binary numbers. -- Grant Edwards grante Yow! ... Blame it on the at BOSSA NOVA!!! visi.com From python.list at tim.thechases.com Sat Jun 3 17:20:09 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 03 Jun 2006 10:20:09 -0500 Subject: integer to binary... In-Reply-To: <12839b8doin7mff@corp.supernews.com> References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> <127ugf9jgu7av18@corp.supernews.com> <4480a084$0$6172$626a54ce@news.free.fr> <12839b8doin7mff@corp.supernews.com> Message-ID: <4481A8A9.4030902@tim.thechases.com> > The fact that they impliment the xor operator is pretty much > proof that integers are stored in binary format -- xor is only > defined for binary numbers. Um...let's not use bad logic/proofs for evidencing this... >>> hasattr(set(), "__xor__") True :) -tkc From grante at visi.com Sat Jun 3 19:18:21 2006 From: grante at visi.com (Grant Edwards) Date: Sat, 03 Jun 2006 17:18:21 -0000 Subject: integer to binary... References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> <127ugf9jgu7av18@corp.supernews.com> <4480a084$0$6172$626a54ce@news.free.fr> <12839b8doin7mff@corp.supernews.com> Message-ID: <1283h2t81mdn697@corp.supernews.com> On 2006-06-03, Tim Chase wrote: >> The fact that they impliment the xor operator is pretty much >> proof that integers are stored in binary format -- xor is only >> defined for binary numbers. > > Um...let's not use bad logic/proofs for evidencing this... > > >>> hasattr(set(), "__xor__") > True Sets aren't numbers. Perhaps I should have phrased it better: xor is only defined for numbers if they are represented in binary. If numbers were represented in something other than binary, then an xor operation on those numbers wouldn't make sense. -- Grant Edwards grante Yow! .. I want to perform at cranial activities with visi.com Tuesday Weld!! From bdesth.quelquechose at free.quelquepart.fr Mon Jun 5 05:11:36 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 05 Jun 2006 05:11:36 +0200 Subject: integer to binary... In-Reply-To: <12839b8doin7mff@corp.supernews.com> References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> <127ugf9jgu7av18@corp.supernews.com> <4480a084$0$6172$626a54ce@news.free.fr> <12839b8doin7mff@corp.supernews.com> Message-ID: <4483714c$0$27378$626a54ce@news.free.fr> Grant Edwards a ?crit : > On 2006-06-02, Bruno Desthuilliers wrote: > >>Grant Edwards a ?crit : >> >>>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. >> >>Not really. > > Yes, really. No, not really. > Otherwise the bitwise boolean operations you > demonstrated wouldn't work as shown. Ho yes ? > >>>>>(7).__class__ >> >> >> >>>>>dir((7)) >> >>['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', >>'__delattr__', '__div__', '__divmod__', '__doc__', '__float__', >>'__floordiv__', '__getattribute__', '__getnewargs__', '__hash__', >>'__hex__', '__init__', '__int__', '__invert__', '__long__', >>'__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', >>'__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', >>'__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', >>'__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', >>'__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', >>'__rxor__', '__setattr__', '__str__', '__sub__', '__truediv__', '__xor__'] >> > > The fact that they impliment the xor operator is pretty much > proof that integers are ... objects, instance of the int class. Not really what I'd call "binary format" !-) Now if you go that way, it's of course true that everything on a computer ends up in a binary format.... It's true. > stored in binary format -- xor is only > defined for binary numbers. > class Prisonner(object): def __xor__(self, other): return "I'm not a (binary) number, I'm a free man" The fact that an object implements the xor operator is pretty much proof that the guy that wrote the class decided to implement the xor operator !-) Grant, I of course agree that, *for practical means*, one can consider that Python's integer are "already in binary format" - for a definition of "binary format" being "you can do bitwise ops on them". But the truth is that Python integers are objects (in the OO meaning) holding integer values - not integer values themselves. 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 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 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 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 bdesth.quelquechose at free.quelquepart.fr Sat Jun 3 01:53:43 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 03 Jun 2006 01:53:43 +0200 Subject: integer to binary... In-Reply-To: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> References: <1149189570.376091.319890@j55g2000cwa.googlegroups.com> Message-ID: <44809ff9$0$6172$626a54ce@news.free.fr> nicolasg at gmail.com a ?crit : > 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... You don't need to convert anything. The bitwise ops are &, |, <<, >> 0 | 2 | 4 -> 6 6 & 2 -> 2 2 << 4 -> 32 8 >> 1 -> 4 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 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 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 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 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 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 bdesth.quelquechose at free.quelquepart.fr Sat Jun 3 01:47:45 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 03 Jun 2006 01:47:45 +0200 Subject: Using print instead of file.write(str) In-Reply-To: <2Iq*Jzbir@news.chiark.greenend.org.uk> References: <2Iq*Jzbir@news.chiark.greenend.org.uk> Message-ID: <44809e93$0$13657$636a55ce@news.free.fr> Sion Arrowsmith a ?crit : > 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 > The reverse isn't true ??? print "".join(str(x) for x in range(10)) (which BTW should be faster, since it's only one I/O, instead of ten with your version.) Now, given: bird = "parrot" beautiful = "dead" How would you do the following with f.write() ? print "this", bird, "is", beautiful (without using string formating, of course...) From timr at probo.com Sun Jun 4 01:06:12 2006 From: timr at probo.com (Tim Roberts) Date: Sat, 03 Jun 2006 23:06:12 GMT Subject: Using print instead of file.write(str) References: <2Iq*Jzbir@news.chiark.greenend.org.uk> <44809e93$0$13657$636a55ce@news.free.fr> Message-ID: <1d5482dibl4b4or8d4fkd90pd17ml3st2p@4ax.com> Bruno Desthuilliers wrote: >Sion Arrowsmith a ?crit : >> 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 > >The reverse isn't true ??? > > print "".join(str(x) for x in range(10)) What he meant it that it is impossible to produce "0123456789" using 10 separate print statements, while it IS possible with 10 separate writes. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From aleax at mac.com Sun Jun 4 02:03:01 2006 From: aleax at mac.com (Alex Martelli) Date: Sat, 3 Jun 2006 17:03:01 -0700 Subject: Using print instead of file.write(str) References: <2Iq*Jzbir@news.chiark.greenend.org.uk> <44809e93$0$13657$636a55ce@news.free.fr> <1d5482dibl4b4or8d4fkd90pd17ml3st2p@4ax.com> Message-ID: <1hgd8io.infymkfhpuerN%aleax@mac.com> Tim Roberts wrote: > Bruno Desthuilliers wrote: > > >Sion Arrowsmith a ?crit : > >> 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 > > > >The reverse isn't true ??? > > > > print "".join(str(x) for x in range(10)) > > What he meant it that it is impossible to produce "0123456789" using 10 > separate print statements, while it IS possible with 10 separate writes. it's not quite impossible, just cumbersome: >>> for x in range(10): ... print x, ... sys.stdout.softspace=0 ... 0123456789>>> Yes, you do need the softspace assignments -- but then, in the write version you need the explicit str calls, so it's not as if in either case you're using "just" the print or write-call. The differences in terms of convenience are surely there (in different circumstances they will favor one or the other of the two approaches), but I don't see such differences in either flexibility or power (if one ignores the issue of convenience, the same tasks can be performed with either approach). Alex From bdesth.quelquechose at free.quelquepart.fr Mon Jun 5 04:49:45 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 05 Jun 2006 04:49:45 +0200 Subject: Using print instead of file.write(str) In-Reply-To: <1d5482dibl4b4or8d4fkd90pd17ml3st2p@4ax.com> References: <2Iq*Jzbir@news.chiark.greenend.org.uk> <44809e93$0$13657$636a55ce@news.free.fr> <1d5482dibl4b4or8d4fkd90pd17ml3st2p@4ax.com> Message-ID: <44836c2c$0$13039$626a54ce@news.free.fr> Tim Roberts a ?crit : > Bruno Desthuilliers wrote: > > >>Sion Arrowsmith a ?crit : >> (snip) >>>"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 >> >>The reverse isn't true ??? >> >> print "".join(str(x) for x in range(10)) > > What he meant it that it is impossible to produce "0123456789" using 10 > separate print statements, while it IS possible with 10 separate writes. why on earth would someone try to use 10 consecutive I/O operations on the same stream when it can be done with 1 ??? From sjmachin at lexicon.net Sun Jun 4 04:52:49 2006 From: sjmachin at lexicon.net (John Machin) Date: Sun, 04 Jun 2006 12:52:49 +1000 Subject: Using print instead of file.write(str) In-Reply-To: <44809e93$0$13657$636a55ce@news.free.fr> References: <2Iq*Jzbir@news.chiark.greenend.org.uk> <44809e93$0$13657$636a55ce@news.free.fr> Message-ID: <44824B01.3040806@lexicon.net> On 3/06/2006 9:47 AM, Bruno Desthuilliers wrote: > > Now, given: > > bird = "parrot" > beautiful = "dead" > > How would you do the following with f.write() ? > > print "this", bird, "is", beautiful > > (without using string formating, of course...) Like this: f.write((' '.join(str(x) for x in ['this', bird, 'is', beautiful]) + '\n')) ... or was that a rhetorical question? Cheers, John From bdesth.quelquechose at free.quelquepart.fr Mon Jun 5 04:52:51 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 05 Jun 2006 04:52:51 +0200 Subject: Using print instead of file.write(str) In-Reply-To: <44824B01.3040806@lexicon.net> References: <2Iq*Jzbir@news.chiark.greenend.org.uk> <44809e93$0$13657$636a55ce@news.free.fr> <44824B01.3040806@lexicon.net> Message-ID: <44836ce6$0$13039$626a54ce@news.free.fr> John Machin a ?crit : (snip) > ... or was that a rhetorical question? It was. 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 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 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 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 rabkinDELETE at mweb.co.za Sun Jun 4 13:58:26 2006 From: rabkinDELETE at mweb.co.za (Max) Date: Sun, 04 Jun 2006 13:58:26 +0200 Subject: if not CGI: In-Reply-To: <447f722b$0$30312$626a54ce@news.free.fr> References: <447f722b$0$30312$626a54ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Max a ?crit : (snip) > > 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. That's what I thought! (snip) > > 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. Good stuff. I'm downloading them now. Thanks. --Max 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 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 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 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 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 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 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 bdesth.quelquechose at free.quelquepart.fr Sat Jun 3 03:42:23 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 03 Jun 2006 03:42:23 +0200 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: <4480b971$0$29643$636a55ce@news.free.fr> Captain Dondo a ?crit : (snip) > 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() Why don't you just add an order by clause in your sql statement ??? > (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)) is the combination of title and starttime a unique key ? Also, unless you have lots of records with huge blobs in 'recorded' table, this smells like a WTF. > selectlist.append(c.fetchone()) > The problem is the last line. I'm afraid this is not the only problem... > I am creating a bunch of tuples that are, > for my purposes, incorrect. selectlist.append(list(c.fetchone)) would create a bunch of lists instead. > 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), No huge blob in sight. And since the list of records fits on a dialog with checkboxes, I think you could easily avoid querying the DB that many times. FWIW, you could probably query it once only. > (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. You can of course turn a tuple into a list, then modify the list. But it would still be a waste of time. Learning the full syntax for a SQL select might be more useful. You can do something like: select item1, item2, 'someconstant', item3, ..., from sometable (...) which avoid having anything to replace. Assuming that title + starttime is the primary key, and - not knowing the structure of your table - assuming that starttime is the second field, title the 5th and subtitle the 6th : # --------------------- sql = """ SELECT f1, starttime, f3, f4, title, subtitle, f7, '%s', f9, (..etc...), f24 FROM recorded ORDER BY title, starttime """ % toGoBackend c.execute(sql) rows = c.fetchall() # seems like dialog.checklist wants strings as tags # tried with ints, but it crashed... choices = [(str(i), row[5], 0) for row in rows] d = dialog.Dialog(dialog="dialog") d.add_persistent_args(["--backtitle", "Myth2Go"]) retcode, indices = d.checklist('', choices=choices) if retcode: # exit or return selectlist = [rows[i] for i in map(int, indices)] # --------------------- HTH 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 __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 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 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 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 paddy3118 at netscape.net Fri Jun 2 00:53:08 2006 From: paddy3118 at netscape.net (Paddy) Date: 1 Jun 2006 15:53:08 -0700 Subject: grouping a flat list of number by range References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> <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 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 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 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 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 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 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 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 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 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 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 joh12005 at yahoo.fr Sat Jun 3 13:50:16 2006 From: joh12005 at yahoo.fr (joh12005 at yahoo.fr) Date: 3 Jun 2006 04:50:16 -0700 Subject: grouping a flat list of number by range In-Reply-To: References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> Message-ID: <1149335416.359226.228600@i39g2000cwa.googlegroups.com> thanks to all ! my version was far less clever/long thant the one you posted, i'm going to examine all these with much interest, and learn... best regards. From joh12005 at yahoo.fr Sun Jun 4 19:57:22 2006 From: joh12005 at yahoo.fr (joh12005 at yahoo.fr) Date: 4 Jun 2006 10:57:22 -0700 Subject: grouping a flat list of number by range In-Reply-To: References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> Message-ID: <1149443841.948685.148840@i39g2000cwa.googlegroups.com> Hello > ... _, first_n = group[0] what is the meaning of the underscore "_" ? is it a special var ? or should it be readed as a way of unpacking a tuple in a non useful var ? like lost, first_n = group[0] best regards. From steven.bethard at gmail.com Sun Jun 4 20:11:21 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 04 Jun 2006 12:11:21 -0600 Subject: grouping a flat list of number by range In-Reply-To: <1149443841.948685.148840@i39g2000cwa.googlegroups.com> References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> <1149443841.948685.148840@i39g2000cwa.googlegroups.com> Message-ID: joh12005 at yahoo.fr wrote: >> ... _, first_n = group[0] > > what is the meaning of the underscore "_" ? is it a special var ? or > should it be readed as a way of unpacking a tuple in a non useful var ? > like > > lost, first_n = group[0] Yep, it's just another name. "lost" would have worked just as well. It's pretty typical around here to see "_" used when a tuple is unpacked but some of the values aren't used. So if you see something like:: for _, dirs, _ in os.walk(top): ... it just means that the "..." code is only going to use "dirs" (not the root path or files that are also available from the os.walk() iterator). STeVe From sreeram at tachyontech.net Sun Jun 4 20:12:20 2006 From: sreeram at tachyontech.net (K.S.Sreeram) Date: Sun, 04 Jun 2006 23:42:20 +0530 Subject: grouping a flat list of number by range In-Reply-To: <1149443841.948685.148840@i39g2000cwa.googlegroups.com> References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> <1149443841.948685.148840@i39g2000cwa.googlegroups.com> Message-ID: <44832284.30203@tachyontech.net> Yup! '_' is just used as a dummy. Its a pretty common idiom. There's nothing special about that variable. joh12005 at yahoo.fr wrote: > Hello > >> ... _, first_n = group[0] > > what is the meaning of the underscore "_" ? is it a special var ? or > should it be readed as a way of unpacking a tuple in a non useful var ? > like > > lost, first_n = group[0] > > best regards. > -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 260 bytes Desc: OpenPGP digital signature URL: From grflanagan at yahoo.co.uk Sat Jun 3 21:27:41 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 3 Jun 2006 12:27:41 -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: <1149362861.558049.172100@j55g2000cwa.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) Just another 'itertools.groupby' variation. It considers the whole range of numbers spanned by the dataset - eg. in your example, range(3,17) - so possibly not very efficient if the range is large and the data sparse within the range. def get_intervals(data): intervals = [ [], [] ] for k,g in groupby(range(data[0],data[-1]+2), lambda x:x in data): intervals[k].append( list(g)[0] ) #k is 0 or 1 return zip(intervals[1],intervals[0]) a = [3, 6, 7, 8, 12, 13, 15] assert get_intervals(a) == [(3,4),(6, 9),(12,14),(15,16)] Gerard From steven.bethard at gmail.com Sun Jun 4 00:21:07 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 03 Jun 2006 16:21:07 -0600 Subject: grouping a flat list of number by range In-Reply-To: <1149362861.558049.172100@j55g2000cwa.googlegroups.com> References: <1149196642.001466.53990@c74g2000cwc.googlegroups.com> <1149362861.558049.172100@j55g2000cwa.googlegroups.com> Message-ID: 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) > > Just another 'itertools.groupby' variation. It considers the whole > range of numbers spanned by the dataset - eg. in your example, > range(3,17) - so possibly not very efficient if the range is large and > the data sparse within the range. > > def get_intervals(data): > intervals = [ [], [] ] > for k,g in groupby(range(data[0],data[-1]+2), lambda x:x in data): > intervals[k].append( list(g)[0] ) #k is 0 or 1 > return zip(intervals[1],intervals[0]) If you're gonna go this route, you should definitely use a set to check containment; ``x in data`` is going to be costly for long lists. Defining your key something like the following would be better:: data_set = set(data) def key(x): return x in data_set STeVe 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 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 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 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 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 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 bdesth.quelquechose at free.quelquepart.fr Sat Jun 3 01:38:55 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 03 Jun 2006 01:38:55 +0200 Subject: Conditional Expressions in Python 2.4 In-Reply-To: <7OidneazQ9UJHB3ZnZ2dnUVZ_sGdnZ2d@comcast.com> References: <4480042b$0$29879$636a55ce@news.free.fr> <7OidneazQ9UJHB3ZnZ2dnUVZ_sGdnZ2d@comcast.com> Message-ID: <44809c81$0$14874$626a54ce@news.free.fr> Steven Bethard a ?crit : > A.M wrote: > > Do we have the conditional expressions in Python 2.4? > > bruno at modulix wrote: > (snip) > >> 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 [] > [] Yes, this is one of the tricky part !-) Always make sure the second term doesn't eval to False. > > >>> def f(): > ... print "don't evaluate me" > ... return 'f' > ... > >>> def g(): > ... return 'g' > ... > >>> (f(), g())[True] Why on earth are you calling the callables *before* testing ? Should be: (f, g)[True]() of course. 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 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 wblock at wonkity.com Sat Jun 3 06:47:24 2006 From: wblock at wonkity.com (Warren Block) Date: Sat, 03 Jun 2006 04:47:24 -0000 Subject: Can Python format long integer 123456789 to 12,3456,789 ? References: <8oKfg.1621$Su3.139425@news20.bellglobal.com> <447f7f43$1@news.eftel.com> Message-ID: John Machin wrote: > 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<--- Why not just port the Perl "commify" code? You're close to it, at least for the regex: # From perldoc perlfaq5 # 1 while s/^([-+]?\d+)(\d{3})/$1,$2/; # Python version import re def commify(n): while True: (n, count) = re.subn(r'^([-+]?\d+)(\d{3})', r'\1,\2', n) if count == 0: break return n -- Warren Block * Rapid City, South Dakota * USA 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: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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 max at alcyone.com Mon Jun 5 23:46:55 2006 From: max at alcyone.com (Erik Max Francis) Date: Mon, 05 Jun 2006 14:46:55 -0700 Subject: C# equivalent to range() In-Reply-To: <1149226573.446484.17340@c74g2000cwc.googlegroups.com> 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: Luis M. Gonz?lez wrote: > 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 :-) Plenty of people _did_ helpfully respond to his question with the right answer. The right answer is: This is the wrong forum; as your question in a C#-related forum. It was then the _original poster_ who became "disagreeable" by assigning motive to the people who _actually helped him_ by telling him the right place to ask his question, saying that the "enjoy to waste their time niggling." He's complaining that people weren't nice to help. But they _were_. They answered his question politely and to the point. It's _he_ that turned rude after that. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis What a crime to waste [youth] on children. -- George Bernard Shaw 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 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: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 tdelaney at avaya.com Mon Jun 5 00:29:58 2006 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Mon, 5 Jun 2006 08:29:58 +1000 Subject: C# equivalent to range() Message-ID: <2773CAC687FD5F4689F526998C7E4E5F074380@au3010avexu1.global.avaya.com> Luis M. Gonz?lez wrote: > 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 :-) Well, there are reasons to reply to a message stating that it's not on-topic for the group. The most common reaction to receiving no replies is to start a new thread petulantly asking why there were no answers to the original thread. If that one gets no replies the most common reaction is start another new thread stating that Python sucks, the newsgroup sucks, etc. Not saying that this is what would have happened in this case, but it is the most common sequence of events. Better to head it off before it happens. At least any upset replies tend to be restricted to the one thread ;) Unfortunately, posting a good response, whilst apparently helpful, tends to encourage further off-topic postings :( Tim Delaney From neuruss at gmail.com Mon Jun 5 02:55:19 2006 From: neuruss at gmail.com (Neuruss) Date: 4 Jun 2006 17:55:19 -0700 Subject: C# equivalent to range() In-Reply-To: References: Message-ID: <1149468919.951745.163700@g10g2000cwb.googlegroups.com> Delaney, Timothy (Tim) wrote: > Well, there are reasons to reply to a message stating that it's not on-topic for the group. The most common reaction to receiving no replies is to start a new thread petulantly asking why there were no answers to the original thread. If that one gets no replies the most common reaction is start another new thread stating that Python sucks, the newsgroup sucks, etc. > > Not saying that this is what would have happened in this case, but it is the most common sequence of events. Better to head it off before it happens. At least any upset replies tend to be restricted to the one thread ;) > > Unfortunately, posting a good response, whilst apparently helpful, tends to encourage further off-topic postings :( > > Tim Delaney Tim, I don't think it was entirely off topic, although I understand your point. It happens that I'm using Ironpython, and I wanted to improve the performance of a script by writing a c# extension. Writing extensions in other languages (c, c++ and now c#) is a common practice amongst python programers, and that was the purpose of my question. I asked especifically the equivalence of a couple of python features in this language. And I did it here, because chances were that someone would understand what I was asking, (which was how to translate those python features into another language). I could have asked this question in a c# related forum, but then I should have had to explain how "range" and "extend" work in python... Actualy, someone replied with a couple of lines, and this was just what I wanted! That person was very kind and I'm sure it didn't take more than a few seconds to write his reply. I'm sure he was satisfied by helping me, and I was satisfied too by his kind reply. What about the others? Are they worried about the storage limit of this forum perhaps? Or it was the wasted bandwidth? What was exactly the reason for being that annoyed? Am I forcing them to read my question or to post a reply? I grant that perhaps I should have explained why I needed this advice. But I'm not using this forum to learn another thing. I am a (budding) python programmer looking for a solution, and my question was very especific and to the point. Anyway, if someone still feels that the question is off topic, there are better ways to point it out (as you're doing now). If these people's life suck, I suggest they buy a punching bag to discharge their frustation. I don't think this forum is the best place for doing it. Regards, Neuruss From neuruss at gmail.com Mon Jun 5 06:27:55 2006 From: neuruss at gmail.com (Neuruss) Date: 4 Jun 2006 21:27:55 -0700 Subject: C# equivalent to range() In-Reply-To: References: <1149468919.951745.163700@g10g2000cwb.googlegroups.com> Message-ID: <1149481675.192638.275140@c74g2000cwc.googlegroups.com> Dennis Lee Bieber wrote: > What most of us saw was a blunt request on how to implement a Python > construct in some other language that may not be familiar to us. I'm curious, who are "us"? From max at alcyone.com Mon Jun 5 08:26:05 2006 From: max at alcyone.com (Erik Max Francis) Date: Sun, 04 Jun 2006 23:26:05 -0700 Subject: C# equivalent to range() In-Reply-To: <1149481675.192638.275140@c74g2000cwc.googlegroups.com> References: <1149468919.951745.163700@g10g2000cwb.googlegroups.com> <1149481675.192638.275140@c74g2000cwc.googlegroups.com> Message-ID: Neuruss wrote: > Dennis Lee Bieber wrote: >> What most of us saw was a blunt request on how to implement a Python >> construct in some other language that may not be familiar to us. > > I'm curious, who are "us"? The regular readers of comp.lang.python. If you don't think we haven't seen this a zillion times before, you're kidding yourself. If you want help on a language, ask in that language's newsgroup/mailing list/forum/whatever. It surprises me how often people don't ask useful questions, or deliberately and knowingly ask questions in the wrong places, and then actually _defend_ their actions after they're politely but firmly informed how to fix the problem. You're really not making yourself look any better by continuing this thread ... -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Democritus may have come from Abdera, but he was no dummy. -- Carl Sagan From neuruss at gmail.com Mon Jun 5 14:18:13 2006 From: neuruss at gmail.com (Neuruss) Date: 5 Jun 2006 05:18:13 -0700 Subject: C# equivalent to range() In-Reply-To: References: <1149468919.951745.163700@g10g2000cwb.googlegroups.com> <1149481675.192638.275140@c74g2000cwc.googlegroups.com> Message-ID: <1149509893.031953.19310@i40g2000cwc.googlegroups.com> Erik Max Francis wrote: > > I'm curious, who are "us"? > > The regular readers of comp.lang.python. If you don't think we haven't > seen this a zillion times before, you're kidding yourself. > > If you want help on a language, ask in that language's newsgroup/mailing > list/forum/whatever. > > It surprises me how often people don't ask useful questions, or > deliberately and knowingly ask questions in the wrong places, and then > actually _defend_ their actions after they're politely but firmly > informed how to fix the problem. You're really not making yourself look > any better by continuing this thread ... Just to finish this thread: 1) It wasn't a blunt question. I started the post apologizing for the (not entirely) off opic question. 2) I wasn't politely informed. It was pretty harshly. 3) If you mean that "us" are the zillion registered users of this mailing list, well buddy, you know a whole lot of people! 4) At least one of these people replied kindly and correctly to my question within seconds. Three of four more spent several minutes whining. The other zilion persons who were not interested (other than the four I mentioned above) silently and peacefully ignored the question on went on with their happy lifes. ? bient?t, Neuruss From fredrik at pythonware.com Mon Jun 5 22:24:48 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 05 Jun 2006 22:24:48 +0200 Subject: C# equivalent to range() In-Reply-To: <1149509893.031953.19310@i40g2000cwc.googlegroups.com> References: <1149468919.951745.163700@g10g2000cwb.googlegroups.com> <1149481675.192638.275140@c74g2000cwc.googlegroups.com> <1149509893.031953.19310@i40g2000cwc.googlegroups.com> Message-ID: Neuruss wrote: > [more childish blah blah blah] do you think the few of us who haven't already done so would miss anything if we plonked you now? From fuzzyman at gmail.com Tue Jun 6 00:05:40 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 5 Jun 2006 15:05:40 -0700 Subject: C# equivalent to range() In-Reply-To: <1149509893.031953.19310@i40g2000cwc.googlegroups.com> References: <1149468919.951745.163700@g10g2000cwb.googlegroups.com> <1149481675.192638.275140@c74g2000cwc.googlegroups.com> <1149509893.031953.19310@i40g2000cwc.googlegroups.com> Message-ID: <1149545140.011616.130610@y43g2000cwc.googlegroups.com> Neuruss wrote: > Erik Max Francis wrote: > > > I'm curious, who are "us"? > > > > The regular readers of comp.lang.python. If you don't think we haven't > > seen this a zillion times before, you're kidding yourself. > > > > If you want help on a language, ask in that language's newsgroup/mailing > > list/forum/whatever. > > > > It surprises me how often people don't ask useful questions, or > > deliberately and knowingly ask questions in the wrong places, and then > > actually _defend_ their actions after they're politely but firmly > > informed how to fix the problem. You're really not making yourself look > > any better by continuing this thread ... > > Just to finish this thread: > 1) It wasn't a blunt question. I started the post apologizing for the > (not entirely) off opic question. > 2) I wasn't politely informed. It was pretty harshly. > 3) If you mean that "us" are the zillion registered users of this > mailing list, well buddy, you know a whole lot of people! > 4) At least one of these people replied kindly and correctly to my > question within seconds. Three of four more spent several minutes > whining. > The other zilion persons who were not interested (other than the four I > mentioned above) silently and peacefully ignored the question on went > on with their happy lifes. > FWIW I agree. If anyone didn't want to answer the question they didn't need to. Why be rude to someone asking a polite question. It's not as if there isn't much more *worse* noise on this group. Fuzzyman http://www.voidspace.org.uk/python/index.shtml > ? bient?t, > Neuruss From max at alcyone.com Tue Jun 6 00:27:08 2006 From: max at alcyone.com (Erik Max Francis) Date: Mon, 05 Jun 2006 15:27:08 -0700 Subject: C# equivalent to range() In-Reply-To: <1149545140.011616.130610@y43g2000cwc.googlegroups.com> References: <1149468919.951745.163700@g10g2000cwb.googlegroups.com> <1149481675.192638.275140@c74g2000cwc.googlegroups.com> <1149509893.031953.19310@i40g2000cwc.googlegroups.com> <1149545140.011616.130610@y43g2000cwc.googlegroups.com> Message-ID: Fuzzyman wrote: > FWIW I agree. If anyone didn't want to answer the question they didn't > need to. > > Why be rude to someone asking a polite question. It's not as if there > isn't much more *worse* noise on this group. Here were the "harsh" and "whining" responses to his question he's complaining about: | Bad guess. Ask questions about language X on comp.lang.X | Really, it isn't. Post in a C# discussion forum, describing the | behaviour you want from your program. | *Very* strong suggestion - read the following link: | | http://www.catb.org/~esr/faqs/smart-questions.html Sorry, if you think those are unacceptable tones for responses to off-topic questions, the real world is going to be something of an unpleasant shock. He asked a question. He was told how to get the answer. No one was rude until _he_ started being rude. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Society attacks early when the individual is helpless. -- B.F. Skinner From fuzzyman at gmail.com Tue Jun 6 00:32:16 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 5 Jun 2006 15:32:16 -0700 Subject: C# equivalent to range() In-Reply-To: References: <1149468919.951745.163700@g10g2000cwb.googlegroups.com> <1149481675.192638.275140@c74g2000cwc.googlegroups.com> <1149509893.031953.19310@i40g2000cwc.googlegroups.com> <1149545140.011616.130610@y43g2000cwc.googlegroups.com> Message-ID: <1149546736.728440.74700@i39g2000cwa.googlegroups.com> Erik Max Francis wrote: > Fuzzyman wrote: > > > FWIW I agree. If anyone didn't want to answer the question they didn't > > need to. > > > > Why be rude to someone asking a polite question. It's not as if there > > isn't much more *worse* noise on this group. > > Here were the "harsh" and "whining" responses to his question he's > complaining about: > Fair enough. Maybe they weren't "harsh" and "whining", just patronising and abrupt. Fuzzyman http://www.voidspace.org.uk/python/index.shtml > | Bad guess. Ask questions about language X on comp.lang.X > > | Really, it isn't. Post in a C# discussion forum, describing the > | behaviour you want from your program. > > | *Very* strong suggestion - read the following link: > | > | http://www.catb.org/~esr/faqs/smart-questions.html > > Sorry, if you think those are unacceptable tones for responses to > off-topic questions, the real world is going to be something of an > unpleasant shock. > > He asked a question. He was told how to get the answer. No one was > rude until _he_ started being rude. > > -- > Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ > San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis > Society attacks early when the individual is helpless. > -- B.F. Skinner From robert.kern at gmail.com Tue Jun 6 00:38:08 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 05 Jun 2006 17:38:08 -0500 Subject: C# equivalent to range() In-Reply-To: <1149546736.728440.74700@i39g2000cwa.googlegroups.com> References: <1149468919.951745.163700@g10g2000cwb.googlegroups.com> <1149481675.192638.275140@c74g2000cwc.googlegroups.com> <1149509893.031953.19310@i40g2000cwc.googlegroups.com> <1149545140.011616.130610@y43g2000cwc.googlegroups.com> <1149546736.728440.74700@i39g2000cwa.googlegroups.com> Message-ID: Fuzzyman wrote: > Erik Max Francis wrote: >>Here were the "harsh" and "whining" responses to his question he's >>complaining about: > > Fair enough. Maybe they weren't "harsh" and "whining", just patronising > and abrupt. Welcome to USENET! -- 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 fuzzyman at gmail.com Tue Jun 6 00:41:44 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 5 Jun 2006 15:41:44 -0700 Subject: C# equivalent to range() In-Reply-To: References: <1149468919.951745.163700@g10g2000cwb.googlegroups.com> <1149481675.192638.275140@c74g2000cwc.googlegroups.com> <1149509893.031953.19310@i40g2000cwc.googlegroups.com> <1149545140.011616.130610@y43g2000cwc.googlegroups.com> <1149546736.728440.74700@i39g2000cwa.googlegroups.com> Message-ID: <1149547304.607625.101670@j55g2000cwa.googlegroups.com> Robert Kern wrote: > Fuzzyman wrote: > > Erik Max Francis wrote: > > >>Here were the "harsh" and "whining" responses to his question he's > >>complaining about: > > > > Fair enough. Maybe they weren't "harsh" and "whining", just patronising > > and abrupt. > > Welcome to USENET! Well, this is true. Doesn't make it a *good* thing of course... :-) Fuzzyman http://www.voidspace.org/python/shareware.shtml > > -- > 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 fredrik at pythonware.com Tue Jun 6 08:23:29 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 06 Jun 2006 08:23:29 +0200 Subject: C# equivalent to range() In-Reply-To: <1149547304.607625.101670@j55g2000cwa.googlegroups.com> References: <1149468919.951745.163700@g10g2000cwb.googlegroups.com> <1149481675.192638.275140@c74g2000cwc.googlegroups.com> <1149509893.031953.19310@i40g2000cwc.googlegroups.com> <1149545140.011616.130610@y43g2000cwc.googlegroups.com> <1149546736.728440.74700@i39g2000cwa.googlegroups.com> <1149547304.607625.101670@j55g2000cwa.googlegroups.com> Message-ID: Fuzzyman wrote: > Well, this is true. Doesn't make it a *good* thing of course... :-) on the other hand, the rules for what works and doesn't on public forums have been finely tuned for many years. that's why "the rules don't apply to me" people like Lee, "Neuruss", and others get the kind of pushback they're getting. and frankly, their approach doesn't work in real life, so what makes you think it would work on the internet? From luismgz at gmail.com Tue Jun 6 00:34:09 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 5 Jun 2006 15:34:09 -0700 Subject: C# equivalent to range() In-Reply-To: <1149545140.011616.130610@y43g2000cwc.googlegroups.com> References: <1149468919.951745.163700@g10g2000cwb.googlegroups.com> <1149481675.192638.275140@c74g2000cwc.googlegroups.com> <1149509893.031953.19310@i40g2000cwc.googlegroups.com> <1149545140.011616.130610@y43g2000cwc.googlegroups.com> Message-ID: <1149546849.406638.83870@i39g2000cwa.googlegroups.com> Fuzzyman wrote: > FWIW I agree. If anyone didn't want to answer the question they didn't > need to. > > Why be rude to someone asking a polite question. It's not as if there > isn't much more *worse* noise on this group. I also agree. Although the question may have appeared out of place, it wasn't totally. The poster asked the question very politely, apologizing in advance for what may be consider an off-topyc question. He also said he only knew python, and he probably wasn't able to explain the intended behaviour he wanted in C# without refering to Python. He is also very right when he says that those who were not interested in the question could have simply ignored it. In exchange, he got a couple of slighty rude replies and an ironic comment. What reaction do you expect from him? From scott.daniels at acm.org Tue Jun 6 01:36:34 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 05 Jun 2006 16:36:34 -0700 Subject: C# equivalent to range() In-Reply-To: <1149546849.406638.83870@i39g2000cwa.googlegroups.com> References: <1149468919.951745.163700@g10g2000cwb.googlegroups.com> <1149481675.192638.275140@c74g2000cwc.googlegroups.com> <1149509893.031953.19310@i40g2000cwc.googlegroups.com> <1149545140.011616.130610@y43g2000cwc.googlegroups.com> <1149546849.406638.83870@i39g2000cwa.googlegroups.com> Message-ID: <4484bb7d$1@nntp0.pdx.net> Luis M. Gonz?lez wrote: > Fuzzyman wrote: >> FWIW I agree. If anyone didn't want to answer the question they didn't >> need to. >> >> Why be rude to someone asking a polite question. It's not as if there >> isn't much more *worse* noise on this group. > > The poster asked the question very politely, apologizing in advance for > what may be consider an off-topyc question. Beginning a post by demonstrating that you know you are violating the conventions of the group is _in_and_of_itself_ rude, and hence even the first post was not a polite question. If this were not true, then all manner of spam would be polite. --Scott David Daniels scott.daniels at acm.org From max at alcyone.com Tue Jun 6 00:27:59 2006 From: max at alcyone.com (Erik Max Francis) Date: Mon, 05 Jun 2006 15:27:59 -0700 Subject: C# equivalent to range() In-Reply-To: <1149509893.031953.19310@i40g2000cwc.googlegroups.com> References: <1149468919.951745.163700@g10g2000cwb.googlegroups.com> <1149481675.192638.275140@c74g2000cwc.googlegroups.com> <1149509893.031953.19310@i40g2000cwc.googlegroups.com> Message-ID: Neuruss wrote: > The other zilion persons who were not interested (other than the four I > mentioned above) silently and peacefully ignored the question on went > on with their happy lifes. That's because many of them have killfiled you. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Society attacks early when the individual is helpless. -- B.F. Skinner From antroy at gmail.com Tue Jun 6 10:21:44 2006 From: antroy at gmail.com (Ant) Date: 6 Jun 2006 01:21:44 -0700 Subject: C# equivalent to range() In-Reply-To: References: <1149468919.951745.163700@g10g2000cwb.googlegroups.com> <1149481675.192638.275140@c74g2000cwc.googlegroups.com> <1149509893.031953.19310@i40g2000cwc.googlegroups.com> Message-ID: <1149582104.349641.252000@g10g2000cwb.googlegroups.com> > That's because many of them have killfiled you. I actually wonder whether anyone does use killfiles. I just can''t imagine the sort of person who writes "plonk" or "welcome to my killfile" etc could bear to miss out on a reply to such a post in case there's more to get angry about! And people who are not riled enough by a post to comment on it probably would'nt be fired up enough to bother killfiling either... From sybrenUSE at YOURthirdtower.com.imagination Tue Jun 6 10:37:22 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 6 Jun 2006 10:37:22 +0200 Subject: C# equivalent to range() References: <1149468919.951745.163700@g10g2000cwb.googlegroups.com> <1149481675.192638.275140@c74g2000cwc.googlegroups.com> <1149509893.031953.19310@i40g2000cwc.googlegroups.com> Message-ID: Erik Max Francis enlightened us with: >> The other zilion persons who were not interested (other than the four I >> mentioned above) silently and peacefully ignored the question on went >> on with their happy lifes. > > That's because many of them have killfiled you. I can say that I didn't killfile him. I just peacefully ignored the question and went on with my happy life - I simply don't know anything about C#. 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 neuruss at gmail.com Tue Jun 6 02:27:07 2006 From: neuruss at gmail.com (Neuruss) Date: 5 Jun 2006 17:27:07 -0700 Subject: C# equivalent to range() In-Reply-To: References: <1149468919.951745.163700@g10g2000cwb.googlegroups.com> <1149481675.192638.275140@c74g2000cwc.googlegroups.com> <1149509893.031953.19310@i40g2000cwc.googlegroups.com> Message-ID: <1149553627.015779.27460@i40g2000cwc.googlegroups.com> Fredrik Lundh wrote: > do you think the few of us who haven't already done so would miss > anything if we plonked you now? Oh, no... How am I supposed to live without you, Freddie? From tdelaney at avaya.com Mon Jun 5 23:31:40 2006 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Tue, 6 Jun 2006 07:31:40 +1000 Subject: C# equivalent to range() Message-ID: <2773CAC687FD5F4689F526998C7E4E5FF1E753@au3010avexu1.global.avaya.com> *Very* strong suggestion - read the following link: http://www.catb.org/~esr/faqs/smart-questions.html Tim Delaney 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 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 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 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 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 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 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 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 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 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: 260 bytes Desc: OpenPGP digital signature URL: 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 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 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 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 dongdonglove8 at hotmail.com Fri Jun 2 09:58:07 2006 From: dongdonglove8 at hotmail.com (python) Date: 2 Jun 2006 00:58:07 -0700 Subject: after del list , when I use it again, prompt 'not defined'.how could i delete its element, but not itself? Message-ID: <1149235087.256704.309360@g10g2000cwb.googlegroups.com> 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 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 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 piet at cs.uu.nl Sat Jun 3 00:53:14 2006 From: piet at cs.uu.nl (Piet van Oostrum) Date: Sat, 03 Jun 2006 00:53:14 +0200 Subject: after del list , when I use it again, prompt 'not defined'.how could i delete its element, but not itself? References: <1149235087.256704.309360@g10g2000cwb.googlegroups.com> <1149236355.221540.136120@y43g2000cwc.googlegroups.com> Message-ID: >>>>> SuperHik (S) escribi?: >S> 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[:] >S> or simply >S> a = [] >>>>>> a >>> [] Then you *have* deleted the list and created a new one, which is different from keeping the list and deleting the elements: >>> a = range(10) >>> b = a >>> del a[:] >>> a [] >>> b [] >>> a.append(100) >>> a [100] >>> b [100] >>> a=[] >>> b [100] >>> -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From bdesth.quelquechose at free.quelquepart.fr Sat Jun 3 19:08:30 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 03 Jun 2006 19:08:30 +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: References: <1149235087.256704.309360@g10g2000cwb.googlegroups.com> <1149236355.221540.136120@y43g2000cwc.googlegroups.com> Message-ID: <4481927b$0$12362$626a54ce@news.free.fr> Piet van Oostrum a ?crit : >>>>>>SuperHik (S) escribi?: > > >>S> 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[:] >> >>S> or simply >>S> a = [] >> >>>>>>>a >>>> >>>>[] > > > Then you *have* deleted the list Not necessarily: >>> a = range(10) >>> b = a >>> id(a) 1078034316 >>> id(b) 1078034316 >>> a is b True >>> a = [] >>> b [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> id(a) 1078043724 >>> id(b) 1078034316 >>> What as been deleted is the association ('binding') between the name 'a' and the list object at 1078034316. This object won't be suppressed until there are no more names bound to it. > and created a new one, which is different > from keeping the list and deleting the elements: indeed !-) 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 bdesth.quelquechose at free.quelquepart.fr Sat Jun 3 02:21:37 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 03 Jun 2006 02:21:37 +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: <1149235087.256704.309360@g10g2000cwb.googlegroups.com> References: <1149235087.256704.309360@g10g2000cwb.googlegroups.com> Message-ID: <4480a683$0$935$626a54ce@news.free.fr> python a ?crit : > 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(): Why naming a function "method" ? > global list1 globals are evil. > list1=['a','b','c','d'] > def method2(): > list2=list1 this makes list2 point to the same object as list1. > list2.remove['a'] > main(): > global list1 > method1() > method2() > print list1[0] > > it prints 'b'. Of course. Python's "variable" are really just names referencing objects. Making two names pointing to the same object does'nt make two different objects, just two references to one object. > > How could I keep the list1 not to change when remove list2's elements? Copy the list. From bdesth.quelquechose at free.quelquepart.fr Sat Jun 3 02:26:03 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 03 Jun 2006 02:26:03 +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: <1149235087.256704.309360@g10g2000cwb.googlegroups.com> References: <1149235087.256704.309360@g10g2000cwb.googlegroups.com> Message-ID: <4480a78d$0$3767$636a55ce@news.free.fr> python a ?crit : > after del list , when I use it again, prompt 'not defined'.how could i > delete its element,but not itself? FWIW, del don't delete an object (not directly at least), it just delete the name<->object association. If (and only if) it was the only name referencing that object, then the object will be disposed too. >>> list1 = [1, 2] >>> list2 = list1 >>> id(list1) 1078043852 >>> id(list2) 1078043852 >>> del list2 >>> list1 [1, 2] >>> list2 Traceback (most recent call last): File "", line 1, in ? NameError: name 'list2' is not defined >>> 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 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 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 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 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 greg at cosc.canterbury.ac.nz Sat Jun 3 11:00:23 2006 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 03 Jun 2006 21:00:23 +1200 Subject: import confused by contents of working directory In-Reply-To: <1149244708.049852.153980@i39g2000cwa.googlegroups.com> References: <1149244708.049852.153980@i39g2000cwa.googlegroups.com> Message-ID: <4ed1cvF1e4gqbU1@individual.net> Jon wrote: > 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? Unless it behaves very differently on Windows from everything else, this isn't quite true. The current directory is only put in the path when using the interpreter interactively. When you do python somefile.py the directory containing somefile.py is put at the beginning of sys.path, not the current directory. So you'd still have the same problem even if you weren't cd'ed to the directory containing the test program. The moral is not to put your test program in the same directory as your package files. (Or if you must, have it delete sys.path[0] before importing anything.) -- Greg 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 kent at kentsjohnson.com Sat Jun 3 03:54:38 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Fri, 02 Jun 2006 21:54:38 -0400 Subject: [ANN] lxml 1.0 released In-Reply-To: References: Message-ID: <4480eade$1_2@newspeer2.tds.net> Stefan Behnel wrote: > 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 Are there any plans to offer a Windows installer? Thanks, Kent From stefan.behnel-n05pAM at web.de Sat Jun 3 14:32:55 2006 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sat, 03 Jun 2006 14:32:55 +0200 Subject: [ANN] lxml 1.0 released In-Reply-To: <4480eade$1_2@newspeer2.tds.net> References: <4480eade$1_2@newspeer2.tds.net> Message-ID: <4481817a$0$11078$9b4e6d93@newsread4.arcor-online.net> Kent Johnson wrote: > Stefan Behnel wrote: >> 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 > > Are there any plans to offer a Windows installer? Already there. :) It just takes a minute longer sometimes, but Windows users are not forgotten. Stefan 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 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 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 greg at cosc.canterbury.ac.nz Sat Jun 3 11:05:31 2006 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 03 Jun 2006 21:05:31 +1200 Subject: Selection in Tkinter Text widget. In-Reply-To: <1149251859.630518.248760@y43g2000cwc.googlegroups.com> References: <1149246483.809582.8310@i39g2000cwa.googlegroups.com> <1149251859.630518.248760@y43g2000cwc.googlegroups.com> Message-ID: <4ed1mjF1eao0mU1@individual.net> Ant wrote: > Strange behaviour though (IMHO), that the selection is only shown if > the widget has focus. It's only strange if you're used to certain platforms. This is normal behaviour in the Macintosh world. One of the original Apple UI Guidelines was that there should only be one selection visible at a time, so that it's always clear what you're operating on. (They seem to be breaking that now in MacOSX, which I think is a backward step...) -- Greg 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: From tdelaney at avaya.com Mon Jun 5 00:35:39 2006 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Mon, 5 Jun 2006 08:35:39 +1000 Subject: Which exceptions are recommended to me handled? Message-ID: <2773CAC687FD5F4689F526998C7E4E5FF1E74B@au3010avexu1.global.avaya.com> Florencio Cano wrote: > 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? If you can validly handle the exception, do so. Otherwise, let it propagate. Valid handling could be (for example) logging the error and using a default value. Note that it's a particularly bad idea to just replace one exception with another exception (not suggesting that that is what you intended - just something I've seen a lot ;) try: int(val) except ValueError: raise MyValueError('Bad value: ' + val) The most important problem here is that you've lost the stack trace from the original exception. The next most important is that anything else that believes it can handle a ValueError now won't be able to. Tim Delaney From fredrik at pythonware.com Mon Jun 5 12:53:39 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 05 Jun 2006 12:53:39 +0200 Subject: Which exceptions are recommended to me handled? In-Reply-To: <2773CAC687FD5F4689F526998C7E4E5FF1E74B@au3010avexu1.global.avaya.com> References: <2773CAC687FD5F4689F526998C7E4E5FF1E74B@au3010avexu1.global.avaya.com> Message-ID: Delaney, Timothy (Tim) wrote: > Note that it's a particularly bad idea to just replace one exception > with another exception (not suggesting that that is what you intended - > just something I've seen a lot ;) > > try: > int(val) > except ValueError: > raise MyValueError('Bad value: ' + val) > > The most important problem here is that you've lost the stack trace from > the original exception. which, in many cases, is a good thing, especially if you replace "int" with a call to some low-level support library. if I call API "foo" to open a data file of some kind, I'm not necessarily interested in an "unsubscriptable error" exception on line 129 in barpath.py, nor is it helping me figure out what's wrong in my program. or do you expose internal implementation details to your end users too, to make sure they don't lose any information? From tdelaney at avaya.com Mon Jun 5 23:29:28 2006 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Tue, 6 Jun 2006 07:29:28 +1000 Subject: Which exceptions are recommended to me handled? Message-ID: <2773CAC687FD5F4689F526998C7E4E5F074383@au3010avexu1.global.avaya.com> Fredrik Lundh wrote: > Delaney, Timothy (Tim) wrote: > >> The most important problem here is that you've lost the stack trace from >> the original exception. > > which, in many cases, is a good thing, especially if you replace "int" > with a call to some low-level support library. if I call API "foo" to > open a data file of some kind, I'm not necessarily interested in an > "unsubscriptable error" exception on line 129 in barpath.py, nor is it > helping me figure out what's wrong in my program. I always prefer to have the stack trace, since it *is* useful to me to figure out what is wrong with my program (or possibly, the library I'm using). > or do you expose internal implementation details to your end users > too, to make sure they don't lose any information? No - but I do log any errors, with stack traces, and as much useful data as possible. That way it's more likely that I can get a useful bug report (they send the log file). Replacing an exception *may* not get in the way if you're wrapping a single statement in the exception. I can't think of another case where it would not get in the way. Chained exceptions change this somewhat, because you don't lose the original information. Tim Delaney 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: 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 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: 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 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 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 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 += ' or %i\n )] +=1\n' % (i+1,) else: codestr += ' or ((r<%g) and %i)\n' % (last, i+1) #return codestr exec codestr result = [] # rescale probability based on frequency for c in chosen: result.append(float(c) / n) return result def draw4(n, lst, precision = 0.01, maxbins=10000): """ Memory/speed tradeoff by coarse quantizing of frequency values. """ assert len(lst)>1, "Corner case NOT covered" assert 0.0 < precision < 1.0 and (1.0/precision) < maxbins binmax = int(1.0/precision) chosenbin = [0] * binmax for i in xrange(n): chosenbin[randrange(binmax)] +=1 left, right = 0, 0 # extract bin range for summation chosen = [0] * len(lst) last = 0.0 for i,p in enumerate(lst): last += p right = int(last/precision) chosen[i] = sum( chosenbin[left:right] ) left = right result = [] # rescale probability based on frequency for c in chosen: result.append(float(c) / n) return result === END CODE === From tjreedy at udel.edu Fri Jun 2 21:22:00 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 2 Jun 2006 15:22:00 -0400 Subject: Sampling a population References: <1149275394.499808.31460@i39g2000cwa.googlegroups.com> Message-ID: "Paddy" wrote in message news:1149275394.499808.31460 at 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. For a set of probabilities that uneven, you *might* do better to sort high to low and do a linear search. Or check the two common cases and then do a binary search on the rest. tjr From roger.miller at nova-sol.com Fri Jun 2 22:51:41 2006 From: roger.miller at nova-sol.com (Roger Miller) Date: 2 Jun 2006 13:51:41 -0700 Subject: Sampling a population References: Message-ID: <1149281501.117141.304060@u72g2000cwu.googlegroups.com> For your example, since the probabilities are all multiples of 0.01 you could make a list of 100 elements. Set one of them to a, 5 of them to b, 50 of them to c, etc. Then just randomly sample from the table (which is O(1)). Of course if the probabilities can be arbitrary floating point values then this won't work. But if you can live with rounding to 3 or 4 digits this is probably the fastest and easiest approach. From robert.kern at gmail.com Fri Jun 2 22:03:16 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 02 Jun 2006 15:03:16 -0500 Subject: Sampling a population In-Reply-To: <44805F53.6090409@sweetapp.com> References: <44805F53.6090409@sweetapp.com> 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). numpy.searchsorted() can do all of the n lookups in C. # Untested. import numpy as np def draw(n, lst): ps = np.cumsum([0.0] + [x[1] for x in lst]) # watch for floating point errors here. It's likely that the last # item won't be quite 1.0 r = np.random.random(n) # n psuedorandom numbers uniform on [0, 1) indices = np.searchsorted(ps, r) # now do what you like with indices, which is an array of indices into # lst. Ed Schofield has an implementation of an algorithm by Marsaglia[1] which turns sampling into a fast table lookup. If your probabilities have limited precision (2**-30 or so rather than the full double precision 2**-52 or so), then this might be an attractive option. [1] http://www.jstatsoft.org/v11/i03/v11i03.pdf The implementation is in the scipy sandbox currently, but I don't think it builds painlessly at the moment. http://svn.scipy.org/svn/scipy/trunk/Lib/sandbox/montecarlo/ Ask on one of the scipy mailing lists if you need help building it. http://www.scipy.org/Mailing_Lists -- 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 brian at sweetapp.com Sat Jun 3 08:11:44 2006 From: brian at sweetapp.com (Brian Quinlan) Date: Sat, 03 Jun 2006 08:11:44 +0200 Subject: Sampling a population In-Reply-To: References: <44805F53.6090409@sweetapp.com> Message-ID: <44812820.8080205@sweetapp.com> Robert Kern wrote: > [numpy implementation snipped] > Ed Schofield has an implementation of an algorithm by Marsaglia[1] which turns > sampling into a fast table lookup. If your probabilities have limited precision > (2**-30 or so rather than the full double precision 2**-52 or so), then this > might be an attractive option. > > [1] http://www.jstatsoft.org/v11/i03/v11i03.pdf > Thanks a lot for the numpy implementation and for the literature reference! I'll try to figure out how little precision I need in my sampling. Cheers, Brian 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 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 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 rpdooling at gmail.com Fri Jun 2 19:47:43 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 2 Jun 2006 10:47:43 -0700 Subject: os.chdir doesn't accept variables sometimes References: <1149267516.348440.60290@u72g2000cwu.googlegroups.com> 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 rdh at new.rr.com Fri Jun 2 21:54:15 2006 From: rdh at new.rr.com (DataSmash) Date: 2 Jun 2006 12:54:15 -0700 Subject: os.chdir doesn't accept variables sometimes In-Reply-To: References: <1149267516.348440.60290@u72g2000cwu.googlegroups.com> Message-ID: <1149278055.629113.47350@c74g2000cwc.googlegroups.com> A simple way to get all the files throughout the directory sturcture... You may have to rewrite the "CONVERTING" part. import os, glob for root, dirs, files in os.walk(os.getcwd()): for file in files: if file.endswith(".mp3"): print "File: " + os.path.abspath(os.path.join(root, file)) print "CONVERTING "+file+" to "+file[:file.index(".")]+".mp3" file = file[:file.index(".")]+".mp3" Donn Cave wrote: > 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 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(' "frexp() result out of range" (was Re: PyExcelerator) In-Reply-To: <1149269975.981840.286750@j55g2000cwa.googlegroups.com> References: <1149269975.981840.286750@j55g2000cwa.googlegroups.com> Message-ID: <4480B495.6010207@lexicon.net> On 3/06/2006 3:39 AM, tkpmep at hotmail.com wrote: > 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 Grumble: When you need to post a traceback, please supply one that shows on each line which *file* the source line is in. In this case there are multiple files, and 9 classes spread over 4 files have a method called get_biff_data. > > 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(' > Any thoughts on what the problem could be? > It is calling struct.pack (see structmodule.c in the Python source) to encode one of your cell values as an 8-byte little-endian IEEE 754 floating-point number. This task is handed off to _PyFloat_Pack8() (see floatobject.c). Here's the relevant bit: """ if (x < 0) { sign = 1; x = -x; } else sign = 0; f = frexp(x, &e); /* Normalize f to be in the range [1.0, 2.0) */ if (0.5 <= f && f < 1.0) { f *= 2.0; e--; } else if (f == 0.0) e = 0; else { PyErr_SetString(PyExc_SystemError, "frexp() result out of range"); return -1; } """ where x is your cell value as a C double. frexp() is a standard C library routine. The above code is just checking that it has done its job correctly. AFAICT from reading K&R v2 p251, the code is correct. Aside: isn't open source wonderful? Well it is for me. It could be wonderful for you too :-) I'm not an IEEE 754 guru by any means, so I'm guessing your value could be an Inf (infinity) or a NaN (not a number) -- there's no explicit test for those in the code -- or you have stumbled on a value that's a corner case on your platform. Maybe it's -0.0 (zero with the sign bit set). Grumble: When you have a problem like this, you should state what version of Python you are using, on what platform. The line you get when you run Python at the command line is a start e.g. """Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on win32""" Please tell us this, plus explicitly what OS and what hardware you are running on. OK, now what's this dodgy number?? Unfortunately, the error is happening right at the end of your process, in the workbook save method. The only info about which row/column is buried deep in pyExcelerator. We don't (yet) want to start poking about there ... Try these steps: 1. Search your alternative CSV output file for the text "Inf" or "NaN" (case insensitive). 2. Put some code in your cell write routine to filter the values you are writing: absval = abs(value) SMALL = 0.000001 # depends on what is reasonable for your app LARGE = 10.0 ** 10 # depends ... if not (value == 0.0 or (SMALL <= absval <= LARGE)): print "strange value %r in row=%d col=%d" % (value, rownum, colnum) Then come back and tell us what if anything you've found. HTH, John 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 jerry.levan at gmail.com Fri Jun 2 21:53:35 2006 From: jerry.levan at gmail.com (jerry.levan at gmail.com) Date: 2 Jun 2006 12:53:35 -0700 Subject: wxPython problems with Fedora Core 5 In-Reply-To: <1149271626.481398.34440@h76g2000cwa.googlegroups.com> References: <1149271626.481398.34440@h76g2000cwa.googlegroups.com> Message-ID: <1149278015.617652.23350@y43g2000cwc.googlegroups.com> writeson wrote: > 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 Check the FC5 Forums, I think the basic answer was to remove the python "compat" rpms. Jerry From frank at chagford.com Sat Jun 3 08:58:53 2006 From: frank at chagford.com (Frank Millman) Date: 2 Jun 2006 23:58:53 -0700 Subject: wxPython problems with Fedora Core 5 In-Reply-To: <1149271626.481398.34440@h76g2000cwa.googlegroups.com> References: <1149271626.481398.34440@h76g2000cwa.googlegroups.com> Message-ID: <1149317933.786386.304070@c74g2000cwc.googlegroups.com> writeson wrote: > 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 Here is a link to a message in the wxpython-users mailing list archive, which apparently gives the solution to your problem. http://tinyurl.com/gf276 I cannot vouch for it. I installed wxPython on FC5 without any problems, using the FC4 binary rpm's from wxPython.org. Hope it works for you. Frank Millman From writeson at charter.net Thu Jun 15 02:35:09 2006 From: writeson at charter.net (writeson) Date: 14 Jun 2006 17:35:09 -0700 Subject: wxPython problems with Fedora Core 5 In-Reply-To: <1149317933.786386.304070@c74g2000cwc.googlegroups.com> References: <1149271626.481398.34440@h76g2000cwa.googlegroups.com> <1149317933.786386.304070@c74g2000cwc.googlegroups.com> Message-ID: <1150331709.388852.50960@u72g2000cwu.googlegroups.com> Frank, Thanks for the link, that solved the problem for me with FC5! That was a great help to me! Doug 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: 260 bytes Desc: OpenPGP digital signature URL: From invalidemail at aerojockey.com Sat Jun 3 03:52:57 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 2 Jun 2006 18:52:57 -0700 Subject: announce: DaVinci Rendering Engine In-Reply-To: References: Message-ID: <1149299576.937958.176450@i40g2000cwc.googlegroups.com> K.S.Sreeram wrote: > 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/ I hope it'll get St. John's face right this time. Carl Banks From noreply at python.org Fri Jun 2 21:12:12 2006 From: noreply at python.org (Returned mail) Date: Fri, 2 Jun 2006 15:12:12 -0400 Subject: Returned mail: see transcript for details Message-ID: <20060602194401.BEF181E400C@bag.python.org> Your message was not delivered due to the following reason(s): Your message could not be delivered because the destination computer was not reachable within the allowed queue period. The amount of time a message is queued before it is returned depends on local configura- tion parameters. Most likely there is a network problem that prevented delivery, but it is also possible that the computer is turned off, or does not have a mail system running right now. Your message was not delivered within 7 days: Server 136.96.117.189 is not responding. The following recipients could not receive this message: Please reply to postmaster at python.org if you feel this message to be in error. From johnjsal at NOSPAMgmail.com Fri Jun 2 21:15:15 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 02 Jun 2006 19:15:15 GMT Subject: can you iterate over a FieldStorage object? Message-ID: <770gg.2223$No6.47403@news.tufts.edu> I'm trying to use a for loop with a FieldStorage object and I get the following error. Can you not treat it like a dictionary, or am I writing the for loop incorrectly? for item in form: print item # or print item.value KeyError Python 2.2.1: /usr/bin/python Fri Jun 2 15:12:36 2006 A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred. /kunden/homepages/7/d159103796/htdocs/labinfo.py 6 print 'content-type: text/html\n' 7 8 form = cgi.FieldStorage(keep_blank_values=True) 9 for item in form: 10 print item item undefined, form = FieldStorage(None, None, [MiniFieldStorage('firs...02116'), MiniFieldStorage('foreignAddress', '')]) /usr/lib/python2.2/cgi.py in __getitem__(self=FieldStorage(None, None, [MiniFieldStorage('firs...02116'), MiniFieldStorage('foreignAddress', '')]), key=0) 548 if item.name == key: found.append(item) 549 if not found: 550 raise KeyError, key 551 if len(found) == 1: 552 return found[0] KeyError undefined, key = 0 KeyError: 0 __doc__ = 'Mapping key not found.' __getitem__ = > __init__ = > __module__ = 'exceptions' __str__ = > args = (0,) From heikki at osafoundation.org Fri Jun 2 21:18:23 2006 From: heikki at osafoundation.org (Heikki Toivonen) Date: Fri, 02 Jun 2006 12:18:23 -0700 Subject: ANN: M2Crypto 0.16beta1 Message-ID: I am happy to announce the first beta of the M2Crypto 0.16 release. Please give these bits a spin and report any problems. I will be making new betas once a week (or more often if needed) until regressions are fixed. I expect the final 0.16 bits will be out by the end of June 2006. Highlights: - All known memory leaks fixed - All known regressions fixed - Added --openssl option to build command which can be used to specify where OpenSSL is installed, by Matt Rodriguez - ECDSA signatures and ECDH key agreement, requires OpenSSL 0.9.8+, by Arno Bakker - Added sha224, sha256, sha384 and sha512, by Larry Bugbee - Added serialNumber, SN, surname, GN and givenName fields to X509_Name, by Martin Paljak - And various other improvements and bugfixes, see CHANGES file Requirements: * Python 2.3 or newer * OpenSSL 0.9.7 or newer o Some optional new features will require OpenSSL 0.9.8 or newer * SWIG 1.3.24 or newer Get it while it's hot from M2Crypto homepage: http://wiki.osafoundation.org/bin/view/Projects/MeTooCrypto -- Heikki Toivonen From lolmcbride at googlemail.com Fri Jun 2 21:31:43 2006 From: lolmcbride at googlemail.com (lolmcbride at googlemail.com) Date: 2 Jun 2006 12:31:43 -0700 Subject: Using pysqlite2 Message-ID: <1149276702.992801.247640@j55g2000cwa.googlegroups.com> Is it possible to use this for sending triggers to a sqlite db?Could someone provide me with an example of how to do this please? Thanks From Dennis.Benzinger at gmx.net Fri Jun 2 22:55:25 2006 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Fri, 02 Jun 2006 22:55:25 +0200 Subject: Using pysqlite2 In-Reply-To: <1149276702.992801.247640@j55g2000cwa.googlegroups.com> References: <1149276702.992801.247640@j55g2000cwa.googlegroups.com> Message-ID: <4480a5c8$1@news.uni-ulm.de> lolmcbride at googlemail.com wrote: > Is it possible to use this for sending triggers to a sqlite db?Could > someone provide me with an example of how to do this please? > Thanks Do you want to implement a trigger for a SQLite database in Python? That won't work. Triggers in SQLite can only contain UPDATE, INSERT, DELETE and SELECT statements http://sqlite.org/lang_createtrigger.html>. Bye, Dennis From gh at ghaering.de Sat Jun 3 01:05:15 2006 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sat, 03 Jun 2006 01:05:15 +0200 Subject: Using pysqlite2 In-Reply-To: <4480a5c8$1@news.uni-ulm.de> References: <1149276702.992801.247640@j55g2000cwa.googlegroups.com> <4480a5c8$1@news.uni-ulm.de> Message-ID: <4480C42B.2030106@ghaering.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Dennis Benzinger wrote: > lolmcbride at googlemail.com wrote: >> Is it possible to use this for sending triggers to a sqlite db?Could >> someone provide me with an example of how to do this please? >> Thanks > > Do you want to implement a trigger for a SQLite database in Python? > > That won't work. Triggers in SQLite can only contain UPDATE, INSERT, > DELETE and SELECT statements http://sqlite.org/lang_createtrigger.html>. Yes, but you can fake it. You can create a new SQL function using pysqlite's create_function, and then just call that function in the trigger. In that Python function from the trigger, you can then even access SQLite again. I've attached a quick-and-dirty example. Note that exceptions in functions get ignored currently, so you better implement a try-except with some kind of logging during development, otherwise you will wonder why nothing happens. Also, older pysqlite releases won't provide useful error messages if you have errors in the SQL you send to executescript(). Using a recent pysqlite release is recommended if you plan to use executescript(). - -- Gerhard -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFEgMQrdIO4ozGCH14RArFaAKCU8lgwidMoNQ0GGKVwJ2GV9xPF8ACfTDhv QVHvudLfoDGiIyFgHe5w6L4= =bfUa -----END PGP SIGNATURE----- -------------- next part -------------- A non-text attachment was scrubbed... Name: trigger_example.py Type: text/x-python Size: 702 bytes Desc: not available URL: From lolmcbride at googlemail.com Wed Jun 7 08:54:19 2006 From: lolmcbride at googlemail.com (xera121) Date: 6 Jun 2006 23:54:19 -0700 Subject: Using pysqlite2 In-Reply-To: References: <1149276702.992801.247640@j55g2000cwa.googlegroups.com> <4480a5c8$1@news.uni-ulm.de> Message-ID: <1149663259.756749.99440@h76g2000cwa.googlegroups.com> Many thanks Gerhard - the solution you offer is workable in the scope of my project. Gracias muchacho Xera121 From alanalan at newsgroup.nospam Fri Jun 2 22:01:17 2006 From: alanalan at newsgroup.nospam (A.M) Date: Fri, 2 Jun 2006 16:01:17 -0400 Subject: Open Source Charting Tool Message-ID: <1L0gg.1841$Su3.159041@news20.bellglobal.com> Hi, I developed a HTML reporting tool that renders Oracle data to HTML and Oracle. At this point I have to add charts (3d bars and pie charts) to this application. I don't think that I have to do it from scratch. Is there any open source charting tool that help me create charts in JPG or gif format? Thanks, Alan From larry.bates at websafe.com Fri Jun 2 22:42:58 2006 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 02 Jun 2006 15:42:58 -0500 Subject: Open Source Charting Tool In-Reply-To: <1L0gg.1841$Su3.159041@news20.bellglobal.com> References: <1L0gg.1841$Su3.159041@news20.bellglobal.com> Message-ID: ReportLab Graphics can do 2D and pie charts, but I don't think it does 3D charts yet. www.reporlab.org Larry Bates A.M wrote: > Hi, > > > > I developed a HTML reporting tool that renders Oracle data to HTML and > Oracle. > > > > At this point I have to add charts (3d bars and pie charts) to this > application. I don't think that I have to do it from scratch. > > > > Is there any open source charting tool that help me create charts in JPG or > gif format? > > > > Thanks, > > Alan > > From alanalan at newsgroup.nospam Fri Jun 2 22:56:55 2006 From: alanalan at newsgroup.nospam (A.M) Date: Fri, 2 Jun 2006 16:56:55 -0400 Subject: Open Source Charting Tool References: <1L0gg.1841$Su3.159041@news20.bellglobal.com> Message-ID: Hi Larry, I can't browse to www.reporlab.org, but I found http://www.reportlab.com/ which has a commercial charting product. Is that what you referring to? Thanks, Alan "Larry Bates" wrote in message news:Z9-dnSpDpb1TPx3ZRVn-iA at comcast.com... > ReportLab Graphics can do 2D and pie charts, but I don't think it does > 3D charts yet. > > www.reporlab.org > > > Larry Bates > > A.M wrote: >> Hi, >> >> >> >> I developed a HTML reporting tool that renders Oracle data to HTML and >> Oracle. >> >> >> >> At this point I have to add charts (3d bars and pie charts) to this >> application. I don't think that I have to do it from scratch. >> >> >> >> Is there any open source charting tool that help me create charts in JPG >> or >> gif format? >> >> >> >> Thanks, >> >> Alan >> >> From felipe.lessa at gmail.com Fri Jun 2 23:13:56 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Fri, 02 Jun 2006 18:13:56 -0300 Subject: Open Source Charting Tool In-Reply-To: References: <1L0gg.1841$Su3.159041@news20.bellglobal.com> Message-ID: <1149282836.4189.5.camel@kenshin.CASA> Em Sex, 2006-06-02 ?s 16:56 -0400, A.M escreveu: > I can't browse to www.reporlab.org, but I found http://www.reportlab.com/ > which has a commercial charting product. Is that what you referring to? ReportLab (the commercial bussiness thing on .com) is where the main developers of ReportLab (a library freely available on www.reporlab.org) work. So what you want really is .org, but apparently it's having problems right now. -- Felipe. From scott.daniels at acm.org Fri Jun 2 23:51:23 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Fri, 02 Jun 2006 14:51:23 -0700 Subject: Open Source Charting Tool In-Reply-To: References: <1L0gg.1841$Su3.159041@news20.bellglobal.com> Message-ID: <4480ae6c$1@nntp0.pdx.net> Felipe Almeida Lessa wrote: > Em Sex, 2006-06-02 ?s 16:56 -0400, A.M escreveu: >> I can't browse to www.reporlab.org, but I found http://www.reportlab.com/ >> which has a commercial charting product. Is that what you referring to? > > ReportLab (the commercial bussiness thing on .com) is where the main > developers of ReportLab (a library freely available on www.reporlab.org) > work. So what you want really is .org, but apparently it's having > problems right now. > Or, you could look for: http://www.reportlab.org/ ------------------------^ --Scott David Daniels scott.daniels at acm.org From larry.bates at websafe.com Sat Jun 3 00:24:01 2006 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 02 Jun 2006 17:24:01 -0500 Subject: Open Source Charting Tool In-Reply-To: <4480ae6c$1@nntp0.pdx.net> References: <1L0gg.1841$Su3.159041@news20.bellglobal.com> <4480ae6c$1@nntp0.pdx.net> Message-ID: <3aCdnbRzDu3gJx3ZnZ2dnUVZ_r-dnZ2d@comcast.com> Ouch. I had a typo. -Larry Scott David Daniels wrote: > Felipe Almeida Lessa wrote: >> Em Sex, 2006-06-02 ?s 16:56 -0400, A.M escreveu: >>> I can't browse to www.reporlab.org, but I found >>> http://www.reportlab.com/ which has a commercial charting product. >>> Is that what you referring to? >> >> ReportLab (the commercial bussiness thing on .com) is where the main >> developers of ReportLab (a library freely available on www.reporlab.org) >> work. So what you want really is .org, but apparently it's having >> problems right now. > Or, you could look for: > http://www.reportlab.org/ > ------------------------^ > > --Scott David Daniels > scott.daniels at acm.org From piet at cs.uu.nl Sat Jun 3 00:58:28 2006 From: piet at cs.uu.nl (Piet van Oostrum) Date: Sat, 03 Jun 2006 00:58:28 +0200 Subject: Open Source Charting Tool References: <1L0gg.1841$Su3.159041@news20.bellglobal.com> Message-ID: >>>>> Felipe Almeida Lessa (FAL) wrote: >FAL> Em Sex, 2006-06-02 ?s 16:56 -0400, A.M escreveu: >>> I can't browse to www.reporlab.org, but I found http://www.reportlab.com/ >>> which has a commercial charting product. Is that what you referring to? >FAL> ReportLab (the commercial bussiness thing on .com) is where the main >FAL> developers of ReportLab (a library freely available on www.reporlab.org) >FAL> work. So what you want really is .org, but apparently it's having >FAL> problems right now. No, but it should really be www.reportlab.org (with the *t*). -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From tchur at optushome.com.au Fri Jun 2 23:59:18 2006 From: tchur at optushome.com.au (Tim Churches) Date: Sat, 03 Jun 2006 07:59:18 +1000 Subject: Open Source Charting Tool In-Reply-To: References: <1L0gg.1841$Su3.159041@news20.bellglobal.com> Message-ID: <4480B4B6.4050905@optushome.com.au> A.M wrote: > I can't browse to www.reporlab.org, but I found http://www.reportlab.com/ > which has a commercial charting product. Is that what you referring to? Typo in the URL. Try http://www.reportlab.org You should also have a look at http://matplotlib.sourceforge.net/ Tim C From felipe.lessa at gmail.com Fri Jun 2 23:04:59 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Fri, 02 Jun 2006 18:04:59 -0300 Subject: Open Source Charting Tool In-Reply-To: References: <1L0gg.1841$Su3.159041@news20.bellglobal.com> Message-ID: <1149282299.4189.2.camel@kenshin.CASA> Em Sex, 2006-06-02 ?s 15:42 -0500, Larry Bates escreveu: > ReportLab Graphics can do 2D and pie charts, but I don't think it does > 3D charts yet. > > www.reporlab.org It does, but I'm not sure if the PNG backend is as good as the PDF one. -- Felipe. From harry.g.george at boeing.com Mon Jun 5 07:09:55 2006 From: harry.g.george at boeing.com (Harry George) Date: Mon, 5 Jun 2006 05:09:55 GMT Subject: Open Source Charting Tool References: <1L0gg.1841$Su3.159041@news20.bellglobal.com> Message-ID: "A.M" writes: > Hi, > > > > I developed a HTML reporting tool that renders Oracle data to HTML and > Oracle. > > > > At this point I have to add charts (3d bars and pie charts) to this > application. I don't think that I have to do it from scratch. > > > > Is there any open source charting tool that help me create charts in JPG or > gif format? > > > > Thanks, > > Alan > > See pygdchart http://www.nullcube.com/software/pygdchart.html -- Harry George PLM Engineering Architecture From belred at gmail.com Mon Jun 5 16:36:14 2006 From: belred at gmail.com (Bryan) Date: Mon, 05 Jun 2006 07:36:14 -0700 Subject: Open Source Charting Tool In-Reply-To: References: <1L0gg.1841$Su3.159041@news20.bellglobal.com> Message-ID: <4484415E.5060401@gmail.com> Harry George wrote: > See pygdchart > http://www.nullcube.com/software/pygdchart.html > this looks pretty nice. i don't see in the docs if and how it can be integrated with other gui toolkits such wxpython. :( bryan From fanmail at micah-wedemeyer.net Fri Jun 2 22:30:04 2006 From: fanmail at micah-wedemeyer.net (Micah) Date: 2 Jun 2006 13:30:04 -0700 Subject: Reversible replacement of whitespace characters with visible characters Message-ID: <1149280203.974237.209080@y43g2000cwc.googlegroups.com> Hi, I'm looking for a tool to do the following 2 things: 1) Given a string (ie. file, std input, whatever), replace all whitespace characters with visible characters (like their Unicode value or something). The end result will be one long unbroken line 2) Given a string altered as in step 1, "decode" it back to the original string. Note: The original string (it will usually be source files) might already contain Unicode values, and these must remain and not be altered in step 2. Note 2: I'm working in a Windows XP environment, but I have access to cygwin if that makes a difference. Can anyone think of a tool that already does this? I could probably whip something up, but if there's already something that does it I'd rather just use it. Micah From jstroud at ucla.edu Fri Jun 2 22:43:19 2006 From: jstroud at ucla.edu (James Stroud) Date: Fri, 02 Jun 2006 13:43:19 -0700 Subject: Reversible replacement of whitespace characters with visible characters In-Reply-To: <1149280203.974237.209080@y43g2000cwc.googlegroups.com> References: <1149280203.974237.209080@y43g2000cwc.googlegroups.com> Message-ID: Micah wrote: > Hi, > > I'm looking for a tool to do the following 2 things: > > 1) Given a string (ie. file, std input, whatever), replace all > whitespace characters with visible characters (like their Unicode value > or something). The end result will be one long unbroken line > > 2) Given a string altered as in step 1, "decode" it back to the > original string. > > Note: The original string (it will usually be source files) might > already contain Unicode values, and these must remain and not be > altered in step 2. > > Note 2: I'm working in a Windows XP environment, but I have access to > cygwin if that makes a difference. > > Can anyone think of a tool that already does this? I could probably > whip something up, but if there's already something that does it I'd > rather just use it. > > Micah > Try urllib. py> import urllib py> astr = 'faf\tfasf dsf\ndsfds dsf dsaf \t\r' py> urllib.quote(astr) 'faf%09fasf%20dsf%0Adsfds%20dsf%20dsaf%20%09%0D' py> print astr faf fasf dsf dsfds dsf dsaf James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From fanmail at micah-wedemeyer.net Fri Jun 2 23:55:38 2006 From: fanmail at micah-wedemeyer.net (Micah) Date: 2 Jun 2006 14:55:38 -0700 Subject: Reversible replacement of whitespace characters with visible characters References: <1149280203.974237.209080@y43g2000cwc.googlegroups.com> Message-ID: <1149285338.168243.22040@c74g2000cwc.googlegroups.com> James Stroud wrote: > Micah wrote: > > Hi, > > > > I'm looking for a tool to do the following 2 things: > > > > 1) Given a string (ie. file, std input, whatever), replace all > > whitespace characters with visible characters (like their Unicode value > > or something). The end result will be one long unbroken line > > > > 2) Given a string altered as in step 1, "decode" it back to the > > original string. > > > > Note: The original string (it will usually be source files) might > > already contain Unicode values, and these must remain and not be > > altered in step 2. > > > > Note 2: I'm working in a Windows XP environment, but I have access to > > cygwin if that makes a difference. > > > > Can anyone think of a tool that already does this? I could probably > > whip something up, but if there's already something that does it I'd > > rather just use it. > > > > Micah > > > > Try urllib. > > py> import urllib > py> astr = 'faf\tfasf dsf\ndsfds dsf dsaf \t\r' > py> urllib.quote(astr) > 'faf%09fasf%20dsf%0Adsfds%20dsf%20dsaf%20%09%0D' > py> print astr > faf fasf dsf > dsfds dsf dsaf > > James > > -- > James Stroud > UCLA-DOE Institute for Genomics and Proteomics > Box 951570 > Los Angeles, CA 90095 > > http://www.jamesstroud.com/ Perfect!! Just what I was looking for! From alikakakhel at yahoo.com Fri Jun 2 23:03:04 2006 From: alikakakhel at yahoo.com (greenflame) Date: 2 Jun 2006 14:03:04 -0700 Subject: Making a second window with Tkinter Message-ID: <1149282184.587252.59160@y43g2000cwc.googlegroups.com> I have a script that will make a window that shows the text I want using Tkinter. What I need to do is to make another window popup above the current window showing other text. I tryed: ----------- from Tkinter imprt * root = Tk() L = Label(root, text="Blah") L.grid(row=0, column=0) # Other labels are also here but their inclusion is not so relavent. root.mainloop() sub = Tk() subL = Label(root, text="Blah") subL.grid(row=0, column=0) sub.mainloop() ---------- However, when I ran the script it only showed the second window after I closed the first one. After looking at the code I guess I can see why. The problem is that I do not know how to fix the issue. Thank you for you help. From jstroud at ucla.edu Fri Jun 2 23:31:23 2006 From: jstroud at ucla.edu (James Stroud) Date: Fri, 02 Jun 2006 14:31:23 -0700 Subject: Making a second window with Tkinter In-Reply-To: <1149282184.587252.59160@y43g2000cwc.googlegroups.com> References: <1149282184.587252.59160@y43g2000cwc.googlegroups.com> Message-ID: greenflame wrote: > I have a script that will make a window that shows the text I want > using Tkinter. What I need to do is to make another window popup above > the current window showing other text. I tryed: > > ----------- > from Tkinter imprt * > > root = Tk() > > L = Label(root, text="Blah") > L.grid(row=0, column=0) > > # Other labels are also here but their inclusion is not so relavent. > > root.mainloop() > > sub = Tk() > > subL = Label(root, text="Blah") > subL.grid(row=0, column=0) > > sub.mainloop() > ---------- > However, when I ran the script it only showed the second window after I > closed the first one. After looking at the code I guess I can see why. > The problem is that I do not know how to fix the issue. Thank you for > you help. > Use Toplevel(). from Tkinter import * root = Tk() def callback(e=None): t = Toplevel() Label(t, text='blah').pack() b = Button(root, text='new top', command=callback) b.pack() root.mainloop() Also, do not do this twice in the same script: Tk(). James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From alikakakhel at yahoo.com Sat Jun 3 05:31:12 2006 From: alikakakhel at yahoo.com (greenflame) Date: 2 Jun 2006 20:31:12 -0700 Subject: Making a second window with Tkinter References: <1149282184.587252.59160@y43g2000cwc.googlegroups.com> Message-ID: <1149305472.893535.67770@h76g2000cwa.googlegroups.com> Ok so I played with your script. Here is a script that more closely mimics what I would like to do except that the way I make the variable deckstr will be different. The only thing I am confused about is that it opens the second window in the beginning and when I click on the button, it does nothing even after I have closed the other window. from Tkinter import * from string import join root = Tk() def showdeck(deck): deckwin = Toplevel() deckstr = join(deck, "\n") Label(deckwin, text=deckstr, justify=LEFT, anchor=W, font="Courier").pack(fill=X) L = Button(root, text="Show Deck", font="Courier", command=showdeck(list('zxcvbnm'))) L.pack() root.mainloop() From rtw at freenet.co.uk Sat Jun 3 11:19:07 2006 From: rtw at freenet.co.uk (Rob Williscroft) Date: Sat, 03 Jun 2006 04:19:07 -0500 Subject: Making a second window with Tkinter References: <1149282184.587252.59160@y43g2000cwc.googlegroups.com> <1149305472.893535.67770@h76g2000cwa.googlegroups.com> Message-ID: greenflame wrote in news:1149305472.893535.67770 @h76g2000cwa.googlegroups.com in comp.lang.python: > Ok so I played with your script. Here is a script that more closely > mimics what I would like to do except that the way I make the variable > deckstr will be different. The only thing I am confused about is that > it opens the second window in the beginning and when I click on the > button, it does nothing even after I have closed the other window. > > from Tkinter import * > from string import join > > root = Tk() > > def showdeck(deck): > deckwin = Toplevel() > deckstr = join(deck, "\n") > Label(deckwin, text=deckstr, justify=LEFT, anchor=W, > font="Courier").pack(fill=X) > > L = Button(root, text="Show Deck", font="Courier", > command=showdeck(list('zxcvbnm'))) You made the buttons command option None (which is what showdeck() returns), you need to make command a function that calls showdeck(list('zxcvbnm')). L = Button(root, text="Show Deck", font="Courier", command= lambda : showdeck(list('zxcvbnm'))) > L.pack() > > root.mainloop() > lambda's docs online: http://docs.python.org/ref/lambdas.html Rob. -- http://www.victim-prime.dsl.pipex.com/ From alikakakhel at yahoo.com Sat Jun 3 23:17:59 2006 From: alikakakhel at yahoo.com (greenflame) Date: 3 Jun 2006 14:17:59 -0700 Subject: Making a second window with Tkinter In-Reply-To: References: <1149282184.587252.59160@y43g2000cwc.googlegroups.com> <1149305472.893535.67770@h76g2000cwa.googlegroups.com> Message-ID: <1149369479.699846.205410@u72g2000cwu.googlegroups.com> What you said about why my code is wrong is still a bit fuzzy but it worked! From fairwinds at eastlink.ca Fri Jun 2 23:15:28 2006 From: fairwinds at eastlink.ca (David Pratt) Date: Fri, 02 Jun 2006 18:15:28 -0300 Subject: Initializing an attribute that needs the object Message-ID: <4480AA70.2020804@eastlink.ca> Hi. I want to have different handlers to do perform logic. The problem is the Handler requires an instance of the factory since it will use its own methods in conjunction with methods of the factory. Once I have got a Factory instance I can give it a new handler (see below). It would be more flexible if I could provide a handle in constructor - but how to do this when it requires the object itself. Would I use a super for this sort of thing? Many thanks Regards, David class Factory: def __init__(self): self.some_handler = Handler(self) f = Factory() f.some_handler = AnotherHandler(f) From marco.giusti at gmail.com Fri Jun 2 23:28:19 2006 From: marco.giusti at gmail.com (Marco Giusti) Date: Fri, 2 Jun 2006 23:28:19 +0200 Subject: Initializing an attribute that needs the object In-Reply-To: <4480AA70.2020804@eastlink.ca> References: <4480AA70.2020804@eastlink.ca> Message-ID: <20060602212819.GA2688@localdomain> On Fri, Jun 02, 2006 at 06:15:28PM -0300, David Pratt wrote: >Hi. I want to have different handlers to do perform logic. The problem >is the Handler requires an instance of the factory since it will use its >own methods in conjunction with methods of the factory. > >Once I have got a Factory instance I can give it a new handler (see >below). It would be more flexible if I could provide a handle in >constructor - but how to do this when it requires the object itself. >Would I use a super for this sort of thing? Many thanks when __init__ is called the object already exists. >class Factory: > > def __init__(self): > self.some_handler = Handler(self) > >f = Factory() >f.some_handler = AnotherHandler(f) try this, should works: class Factory: def __init__(self): self._some_handler = AnotherHandler(self) maybe a class hierarchy is good for you ciao m. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From fairwinds at eastlink.ca Fri Jun 2 23:45:24 2006 From: fairwinds at eastlink.ca (David Pratt) Date: Fri, 02 Jun 2006 18:45:24 -0300 Subject: Initializing an attribute that needs the object In-Reply-To: <20060602212819.GA2688@localdomain> References: <4480AA70.2020804@eastlink.ca> <20060602212819.GA2688@localdomain> Message-ID: <4480B174.5090403@eastlink.ca> Hi Marco. Thanks for your reply. I am providing the handler with the factory instance as I have shown. This is how my code currently works. What I am trying to figure out is how to possibly provide the handler in the constructor when it needs the factory instance. This would give me some better flexibility. ie. class Factory def __init__(self, factory): At this point I don't have self. Would super help me? Regards, David Marco Giusti wrote: > On Fri, Jun 02, 2006 at 06:15:28PM -0300, David Pratt wrote: >> Hi. I want to have different handlers to do perform logic. The problem >> is the Handler requires an instance of the factory since it will use its >> own methods in conjunction with methods of the factory. >> >> Once I have got a Factory instance I can give it a new handler (see >> below). It would be more flexible if I could provide a handle in >> constructor - but how to do this when it requires the object itself. >> Would I use a super for this sort of thing? Many thanks > > when __init__ is called the object already exists. > >> class Factory: >> >> def __init__(self): >> self.some_handler = Handler(self) >> >> f = Factory() >> f.some_handler = AnotherHandler(f) > > try this, should works: > > class Factory: > > def __init__(self): > self._some_handler = AnotherHandler(self) > > maybe a class hierarchy is good for you > > ciao > m. > From fairwinds at eastlink.ca Fri Jun 2 23:47:43 2006 From: fairwinds at eastlink.ca (David Pratt) Date: Fri, 02 Jun 2006 18:47:43 -0300 Subject: Initializing an attribute that needs the object In-Reply-To: <4480B174.5090403@eastlink.ca> References: <4480AA70.2020804@eastlink.ca> <20060602212819.GA2688@localdomain> <4480B174.5090403@eastlink.ca> Message-ID: <4480B1FF.5020009@eastlink.ca> My apologies. What I meant to write was this class Factory def __init__(self, handler): David Pratt wrote: > Hi Marco. Thanks for your reply. I am providing the handler with the > factory instance as I have shown. This is how my code currently works. > What I am trying to figure out is how to possibly provide the handler in > the constructor when it needs the factory instance. This would give me > some better flexibility. > > ie. > > class Factory > > def __init__(self, factory): > > At this point I don't have self. Would super help me? > > Regards, > David > > > Marco Giusti wrote: >> On Fri, Jun 02, 2006 at 06:15:28PM -0300, David Pratt wrote: >>> Hi. I want to have different handlers to do perform logic. The problem >>> is the Handler requires an instance of the factory since it will use its >>> own methods in conjunction with methods of the factory. >>> >>> Once I have got a Factory instance I can give it a new handler (see >>> below). It would be more flexible if I could provide a handle in >>> constructor - but how to do this when it requires the object itself. >>> Would I use a super for this sort of thing? Many thanks >> when __init__ is called the object already exists. >> >>> class Factory: >>> >>> def __init__(self): >>> self.some_handler = Handler(self) >>> >>> f = Factory() >>> f.some_handler = AnotherHandler(f) >> try this, should works: >> >> class Factory: >> >> def __init__(self): >> self._some_handler = AnotherHandler(self) >> >> maybe a class hierarchy is good for you >> >> ciao >> m. >> From bdesth.quelquechose at free.quelquepart.fr Sat Jun 3 04:03:21 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 03 Jun 2006 04:03:21 +0200 Subject: Initializing an attribute that needs the object In-Reply-To: References: Message-ID: <4480be5b$0$27367$626a54ce@news.free.fr> David Pratt a ?crit : > Hi. I want to have different handlers to do perform logic. The problem > is the Handler requires an instance of the factory since it will use its > own methods in conjunction with methods of the factory. > > Once I have got a Factory instance I can give it a new handler (see > below). It would be more flexible if I could provide a handle in > constructor - but how to do this when it requires the object itself. Hint : Python classes are objects too. > class Factory: Do yourself a favour : use new-style classes. class Factory(object): def __init__(self, handler_class): self.handler = handler_class(self) class SomeHandler(object): def __init__(self, factory): self.factory = factory f = Factory(SomeHandler) From fairwinds at eastlink.ca Sat Jun 3 01:17:02 2006 From: fairwinds at eastlink.ca (David Pratt) Date: Fri, 02 Jun 2006 20:17:02 -0300 Subject: Initializing an attribute that needs the object In-Reply-To: <4480be5b$0$27367$626a54ce@news.free.fr> References: <4480be5b$0$27367$626a54ce@news.free.fr> Message-ID: <4480C6EE.1090909@eastlink.ca> Hi Bruno. This is certainly what I was missing. Thank you. I am afraid I am behind the times with use of object. Will I only use object when I am not subclassing? Where will I find a document that provides info on the use of object in new style classes? Many thanks. Regards, David Bruno Desthuilliers wrote: > David Pratt a ?crit : >> Hi. I want to have different handlers to do perform logic. The problem >> is the Handler requires an instance of the factory since it will use its >> own methods in conjunction with methods of the factory. >> >> Once I have got a Factory instance I can give it a new handler (see >> below). It would be more flexible if I could provide a handle in >> constructor - but how to do this when it requires the object itself. > > Hint : Python classes are objects too. > >> class Factory: > > Do yourself a favour : use new-style classes. > > class Factory(object): > def __init__(self, handler_class): > self.handler = handler_class(self) > > class SomeHandler(object): > def __init__(self, factory): > self.factory = factory > > f = Factory(SomeHandler) From sjmachin at lexicon.net Sat Jun 3 01:40:55 2006 From: sjmachin at lexicon.net (John Machin) Date: Sat, 03 Jun 2006 09:40:55 +1000 Subject: Initializing an attribute that needs the object In-Reply-To: References: <4480be5b$0$27367$626a54ce@news.free.fr> Message-ID: <4480CC87.8050006@lexicon.net> On 3/06/2006 9:17 AM, David Pratt **TOPPOSTED**: > Hi Bruno. This is certainly what I was missing. Thank you. I am afraid I > am behind the times with use of object. Will I only use object when I am > not subclassing? More precisely, don't use object when you are subclassing. > Where will I find a document that provides info on the > use of object in new style classes? > Other way up :-) A new-style class is one which inherits ultimately from the type that is called "object". class NewStyleClass(object): pass class OldStyleClass(): pass Docs are a bit ummmm ... See this: http://www.python.org/doc/newstyle/ HTH, John From fairwinds at eastlink.ca Sat Jun 3 14:46:44 2006 From: fairwinds at eastlink.ca (David Pratt) Date: Sat, 03 Jun 2006 09:46:44 -0300 Subject: Initializing an attribute that needs the object In-Reply-To: <4480CC87.8050006@lexicon.net> References: <4480be5b$0$27367$626a54ce@news.free.fr> <4480CC87.8050006@lexicon.net> Message-ID: <448184B4.7090107@eastlink.ca> Hi John. Thank you for the tips and the link. This is helpful. Many thanks. Regards David > A new-style class is one which inherits ultimately from the type that is > called "object". > > class NewStyleClass(object): > pass > > class OldStyleClass(): > pass > > Docs are a bit ummmm ... > See this: http://www.python.org/doc/newstyle/ > > HTH, > John > From bdesth.quelquechose at free.quelquepart.fr Sat Jun 3 19:02:58 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 03 Jun 2006 19:02:58 +0200 Subject: Initializing an attribute that needs the object In-Reply-To: References: <4480be5b$0$27367$626a54ce@news.free.fr> Message-ID: <4481912f$0$20730$636a55ce@news.free.fr> David Pratt a ?crit : David, please, don't top-post (fixed) > > Bruno Desthuilliers wrote: > (snip) >> >> Hint : Python classes are objects too. >> >> >> class Factory(object): >> def __init__(self, handler_class): >> self.handler = handler_class(self) >> >> class SomeHandler(object): >> def __init__(self, factory): >> self.factory = factory >> >> f = Factory(SomeHandler) > Hi Bruno. This is certainly what I was missing. Thank you. I am afraid I > am behind the times with use of object. Will I only use object when I am > not subclassing? If you subclass from a new-style class (almost all classes in the standard lib are...), you don't need to anything more.Else, yes, inherit from 'object', or set 'type' as the metaclass. Both classes defined below are 'new-style' classes: class Parrot: __metaclass__ = type class CheeseChop(object): pass And now: class DeadParrot(Parrot): pass is a new-style class too. > Where will I find a document that provides info on the > use of object in new style classes? In the Fine Manual(tm), of course. Googling python.org for "type unification" or "new-style" should give relevant answers. From alet at librelogiciel.com Fri Jun 2 23:23:53 2006 From: alet at librelogiciel.com (Jerome Alet) Date: Fri, 02 Jun 2006 23:23:53 +0200 Subject: [ANN] pkipplib v0.04 is out Message-ID: Hi there, I'm pleased to announce pkipplib v0.04 This GPLed Python library allows you to create, manage or parse IPP (Internet Printing Protocol) requests. In addition, it exposes a CUPS() class which allows one to interact with a CUPS print server (or an IPP printer). Written in pure Python, there's no need to link with the CUPS' libraries, and it doesn't even require any CUPS related software to work. The mid to long term goal is to support all of the CUPS' IPP API. Summary of changes : - Support for HTTP Basic authentication when connecting to a CUPS server was added. - General reliability was improved. To learn more about it, see examples of use, or download it : http://www.pykota.com/software/pkipplib/ Thank you for reading. Jerome Alet From alet at librelogiciel.com Fri Jun 2 23:30:17 2006 From: alet at librelogiciel.com (Jerome Alet) Date: Fri, 02 Jun 2006 23:30:17 +0200 Subject: [ANN] pkipplib v0.04 is out Message-ID: Hi there, I'm pleased to announce pkipplib v0.04 This GPLed Python library allows you to create, manage or parse IPP (Internet Printing Protocol) requests. In addition, it exposes a CUPS() class which allows one to interact with a CUPS print server (or an IPP printer). Written in pure Python, there's no need to link with the CUPS' libraries, and it doesn't even require any CUPS related software to work. The mid to long term goal is to support all of the CUPS' IPP API. Summary of changes : - Support for HTTP Basic authentication when connecting to a CUPS server was added. - General reliability was improved. To learn more about it, see examples of use, or download it : http://www.pykota.com/software/pkipplib/ Thank you for reading. Jerome Alet From victimorcrime at yahoo.com Sat Jun 3 00:41:53 2006 From: victimorcrime at yahoo.com (RJ) Date: Fri, 2 Jun 2006 18:41:53 -0400 Subject: beginner code problem Message-ID: <2006060218415316807-victimorcrime@yahoocom> I'm trying to teach myself Python (probably running into the old dog new tricks issue) and I'm trying to start with the very basics to get a handle on them. I'm trying to write code to get the computer to flip a coin 100 times and give me the output of how many times heads and tails. After solving a few syntax errors I seem to be stuck in an endless loop and have to kill python. A few times I would get it to print 'heads 0 (or 1) times and tails 1 (or 0) times' 100 times. Here's the code I wrote: import random flip = random.randrange(2) heads = 0 tails = 0 count = 0 while count < 100: if flip == 0: heads += 1 else: tails += 1 count += 1 print "The coin landed on heads", heads, 'times ' \ "and tails", tails, 'times' From sjmachin at lexicon.net Sat Jun 3 01:25:28 2006 From: sjmachin at lexicon.net (John Machin) Date: Sat, 03 Jun 2006 09:25:28 +1000 Subject: beginner code problem In-Reply-To: <2006060218415316807-victimorcrime@yahoocom> References: <2006060218415316807-victimorcrime@yahoocom> Message-ID: <4480C8E8.50800@lexicon.net> On 3/06/2006 8:41 AM, RJ wrote: > I'm trying to teach myself Python (probably running into the old dog > new tricks issue) and I'm trying to start with the very basics to get a > handle on them. > > I'm trying to write code to get the computer to flip a coin 100 times > and give me the output of how many times heads and tails. After solving > a few syntax errors I seem to be stuck in an endless loop and have to > kill python. This can't happen with the code that you posted. It *could* happen if the statement count += 1 was not being executed once each time around the while loop -- like if it was *not* indented. # Bad code #1 import random flip = random.randrange(2) heads = tails = count = 0 while count < 100: if flip == 0: heads += 1 else: tails += 1 count += 1 print "The coin landed on heads", heads, 'times ' \ "and tails", tails, 'times' > A few times I would get it to print 'heads 0 (or 1) times > and tails 1 (or 0) times' 100 times. Again, can't happen with the code you have posted. If it is printing 100 times, that would be because you have indented the print statement so that it is being executed once each trip around the loop. # Bad code #2 import random flip = random.randrange(2) heads = tails = count = 0 while count < 100: if flip == 0: heads += 1 else: tails += 1 count += 1 print "The coin landed on heads", heads, 'times ' \ "and tails", tails, 'times' > > Here's the code I wrote: > > import random > > flip = random.randrange(2) > heads = 0 > tails = 0 > count = 0 > > while count < 100: To help you see what is happening, insert a print statement here; e.g.: print flip, count, heads, tails > > if flip == 0: > heads += 1 > > else: > tails += 1 > > > count += 1 > > > > print "The coin landed on heads", heads, 'times ' \ > "and tails", tails, 'times' > The code that you posted sets flip only once i.e. only 1 toss, not 100. If it is 0, you get 100 heads and 0 tails. Otherwise you get 0 heads and 100 tails. You need to get a new value for flip each trip. # Not quite so bad code import random heads = tails = count = 0 while count < 100: flip = random.randrange(2) # print flip, count, heads, tails # un-comment as/when required :-) if flip == 0: heads += 1 else: tails += 1 count += 1 print "The coin landed on heads", heads, 'times ' \ "and tails", tails, 'times' HTH, John From prophet621 at cox.net Sat Jun 3 02:09:30 2006 From: prophet621 at cox.net (Rob Johnson) Date: Fri, 2 Jun 2006 20:09:30 -0400 Subject: beginner code problem References: <2006060218415316807-victimorcrime@yahoocom> <4480C8E8.50800@lexicon.net> Message-ID: <2006060220093075249-prophet621@coxnet> On 2006-06-02 19:25:28 -0400, John Machin said: > Thanks for the reply John. I seem to be getting all the same problems > with your code that I had with mine so it may be an issue with Python > on this computer though I haven't had one prior to now. I'm running it > on OSX Tiger so I'll give it a shot on my Windows box. With pythons > portability I didn't think it would be an issue so didn't mention it in > the post. The different problems I was having was a result of moving some of the code around thinking I had messed up and trying to fix it. The code I posted was just running but never stopping to give the the output. Thanks for explaining about getting a new value for flip, I wasn't positive about that and you really helped clear up any confusion I was having. Rob > > This can't happen with the code that you posted. It *could* happen if > the statement count += 1 was not being executed once each time around > the while loop -- like if it was *not* indented. > > # Bad code #1 > import random > flip = random.randrange(2) > heads = tails = count = 0 > while count < 100: > if flip == 0: > heads += 1 > else: > tails += 1 > count += 1 > print "The coin landed on heads", heads, 'times ' \ > "and tails", tails, 'times' > >> A few times I would get it to print 'heads 0 (or 1) times and tails 1 >> (or 0) times' 100 times. > > Again, can't happen with the code you have posted. If it is printing > 100 times, that would be because you have indented the print statement > so that it is being executed once each trip around the loop. > > # Bad code #2 > import random > flip = random.randrange(2) > heads = tails = count = 0 > while count < 100: > if flip == 0: > heads += 1 > else: > tails += 1 > count += 1 > print "The coin landed on heads", heads, 'times ' \ > "and tails", tails, 'times' > >> >> Here's the code I wrote: >> >> import random >> >> flip = random.randrange(2) >> heads = 0 >> tails = 0 >> count = 0 >> >> while count < 100: > > To help you see what is happening, insert a print statement here; e.g.: > print flip, count, heads, tails >> >> if flip == 0: >> heads += 1 >> else: >> tails += 1 >> >> count += 1 >> >> print "The coin landed on heads", heads, 'times ' \ >> "and tails", tails, 'times' >> > > The code that you posted sets flip only once i.e. only 1 toss, not 100. > If it is 0, you get 100 heads and 0 tails. Otherwise you get 0 heads > and 100 tails. You need to get a new value for flip each trip. > > # Not quite so bad code > import random > heads = tails = count = 0 > while count < 100: > flip = random.randrange(2) > # print flip, count, heads, tails # un-comment as/when required :-) > if flip == 0: > heads += 1 > else: > tails += 1 > count += 1 > print "The coin landed on heads", heads, 'times ' \ > "and tails", tails, 'times' > > HTH, > John From uval at rz.uni-karlsruhe.de Sat Jun 3 01:35:09 2006 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Sch=FCle_Daniel?=) Date: Sat, 03 Jun 2006 01:35:09 +0200 Subject: beginner code problem In-Reply-To: <2006060218415316807-victimorcrime@yahoocom> References: <2006060218415316807-victimorcrime@yahoocom> Message-ID: Hello > Here's the code I wrote: > > import random > > flip = random.randrange(2) > heads = 0 > tails = 0 > count = 0 > > while count < 100: > > if flip == 0: flip never changes again it's not reassigned in the while loop > heads += 1 > > else: > tails += 1 > > > count += 1 > > > > print "The coin landed on heads", heads, 'times ' \ > "and tails", tails, 'times' > in case you know how many times to iterate it's better to use for loop (in python and eq C also) from random import randrange as flip result = [0,0] for i in range(100): result[flip(2)] += 1 or from random import randrange as flip result = {"head":0, "tail":0} for i in range(100): result[["head","tail"]flip(2)] += 1 or >>> class Coin: ... def flip(self): ... import random ... return ("head", "tail")[random.randrange(2)] c = Coin() result = {"head":0,"tail":0} for i in range(100): result[c.flip()] += 1 or many many more the important thing is .. to know what is the most suitable data representation for you is it throw-away-code or is this going to be read by other people .. etc hth, Daniel From asma61 at dsl.pipex.com Sat Jun 3 01:56:06 2006 From: asma61 at dsl.pipex.com (DaveM) Date: Sat, 03 Jun 2006 00:56:06 +0100 Subject: beginner code problem References: <2006060218415316807-victimorcrime@yahoocom> Message-ID: On Fri, 2 Jun 2006 18:41:53 -0400, RJ wrote: > I'm trying to teach myself Python (probably running into the old dog >new tricks issue) and I'm trying to start with the very basics to get a >handle on them. > > I'm trying to write code to get the computer to flip a coin 100 times >and give me the output of how many times heads and tails. After solving >a few syntax errors I seem to be stuck in an endless loop and have to >kill python. A few times I would get it to print 'heads 0 (or 1) times >and tails 1 (or 0) times' 100 times. > >Here's the code I wrote: > >import random > >flip = random.randrange(2) >heads = 0 >tails = 0 >count = 0 > >while count < 100: > > if flip == 0: > heads += 1 > > else: > tails += 1 > > > count += 1 > > > >print "The coin landed on heads", heads, 'times ' \ > "and tails", tails, 'times' Several problems here. "flip" is defined just once, so you'll either have 100 heads or tails and your whitespace is all wrong - that's important in Python. Here's how it should look: import random def coinflip(): heads = 0 tails = 0 for goes in range(100): if random.randrange(2) == 1: heads += 1 else: tails += 1 print "heads", heads print "tails", tails if __name__ == "__main__": coinflip() From reply.in.the.newsgroup at my.address.is.invalid Sat Jun 3 03:03:02 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sat, 03 Jun 2006 03:03:02 +0200 Subject: beginner code problem References: <2006060218415316807-victimorcrime@yahoocom> Message-ID: <8on182l21bp9fg8omqiq68vddhc42j87d5@4ax.com> RJ: >import random >flip = random.randrange(2) >heads = 0 >tails = 0 >count = 0 >while count < 100: > if flip == 0: > heads += 1 > else: > tails += 1 > count += 1 Since flip isn't changed in the loop, this is going to report 100 heads or 100 tails, depending on the zeroness of flip. -- Ren? Pijlman From victimorcrime at yahoo.com Sat Jun 3 04:32:13 2006 From: victimorcrime at yahoo.com (RJ) Date: Fri, 02 Jun 2006 22:32:13 -0400 Subject: beginner code problem References: <2006060218415316807-victimorcrime@yahoocom> Message-ID: <1js1821c2hlj77132f758pv371ttb0o3a4@4ax.com> Thanks for all the help and examples. As I mentioned, I'm trying to teach myself and starting with the basics (if, elif, else, while, for, raw_input, int are about all I know so far and don't know that well yet) Some of the example posted are still beyond my understanding but it's good to see other ways of acheiving the result and other things to look up and read about. I've read a bit about Python but only really started trying yesterday. Right now I'm still strugling but with practice I hope for it to come easier and I'll keep learning more syntax. I didn't even think about random.randrange being out of the loop but it makes sence now. Chalk it up to a newbie mistake and a learning experience. I really do appreciate the help and I'm sure this is only the first of many questions I'll have. It's good to know that there are others who can help me understand my mistakes. Rob From dodgyville at gmail.com Sat Jun 3 01:51:02 2006 From: dodgyville at gmail.com (Luke Miller) Date: Sat, 3 Jun 2006 09:51:02 +1000 Subject: Seg fault in python extension module Message-ID: Hello, I am working on my first python module based on a c program. The module builds and installs OK using dist-utils, and imports fine into python. However, when I try and use the one wrapper ("modgl.glVertex4f(1, 2, 3, 1)") in the module, it seg faults. Can anyone spot why this isn't working, or recommend a way to debug these things. Thanks, Luke #include static PyObject *_wrap_glVertex4f(PyObject *self, PyObject *args) { PyObject *resultobj = NULL; float arg1 ; float arg2 ; float arg3 ; float arg4 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; PyObject * obj2 = 0 ; PyObject * obj3 = 0 ; if(!PyArg_ParseTuple(args,(char *)"OOOO:glVertex4f",&obj0,&obj1,&obj2,&obj3)) goto fail; { arg1 = (float)(PyFloat_AsDouble(obj0)); } { arg2 = (float)(PyFloat_AsDouble(obj1)); } { arg3 = (float)(PyFloat_AsDouble(obj2)); } { arg4 = (float)(PyFloat_AsDouble(obj3)); } glVertex4f(arg1,arg2,arg3,arg4); Py_INCREF(Py_None); resultobj = Py_None; return resultobj; fail: return NULL; }; static PyMethodDef modglMethods[] = { { (char *)"glVertex4f", _wrap_glVertex4f, METH_VARARGS, NULL}, { NULL, NULL, 0, NULL } }; PyMODINIT_FUNC modgl(void) { (void) Py_InitModule("modgl", modglMethods); }; int main(int argc, char *argv[]) { /* Pass argv[0] to the Python interpreter */ Py_SetProgramName(argv[0]); /* Initialize the Python interpreter. Required. */ Py_Initialize(); /* Add a static module */ initmodgl(); return 0; }; From sjmachin at lexicon.net Sat Jun 3 04:12:20 2006 From: sjmachin at lexicon.net (John Machin) Date: Sat, 03 Jun 2006 12:12:20 +1000 Subject: Seg fault in python extension module In-Reply-To: References: Message-ID: <4480F004.7000602@lexicon.net> On 3/06/2006 9:51 AM, Luke Miller wrote: > Hello, > > I am working on my first python module based on a c program. The > module builds and installs OK using dist-utils, and imports fine into > python. However, when I try and use the one wrapper > ("modgl.glVertex4f(1, 2, 3, 1)") in the module, it seg faults. > > Can anyone spot why this isn't working, or recommend a way to debug > these things. > > Thanks, > Luke > > #include > > static PyObject *_wrap_glVertex4f(PyObject *self, PyObject *args) { > PyObject *resultobj = NULL; > float arg1 ; > float arg2 ; > float arg3 ; > float arg4 ; > PyObject * obj0 = 0 ; > PyObject * obj1 = 0 ; > PyObject * obj2 = 0 ; > PyObject * obj3 = 0 ; > > if(!PyArg_ParseTuple(args,(char > *)"OOOO:glVertex4f",&obj0,&obj1,&obj2,&obj3)) goto fail; > { > arg1 = (float)(PyFloat_AsDouble(obj0)); Not testing for an error after an API call is just asking for trouble. > } > { > arg2 = (float)(PyFloat_AsDouble(obj1)); > } > { > arg3 = (float)(PyFloat_AsDouble(obj2)); > } > { > arg4 = (float)(PyFloat_AsDouble(obj3)); > } You are making it really hard for yourself. Try this: if(!PyArg_ParseTuple(args,"ffff:glVertex4f",&arg1,&arg2 etc etc The batteries are already included. Using the code for the precise type that you want gives you checking for type mismatches, a with sensible error message. > glVertex4f(arg1,arg2,arg3,arg4); You don't declare this function before calling it. That's dangerous. > > Py_INCREF(Py_None); resultobj = Py_None; > return resultobj; > fail: > return NULL; > }; > > > static PyMethodDef modglMethods[] = { > { (char *)"glVertex4f", _wrap_glVertex4f, METH_VARARGS, NULL}, > { NULL, NULL, 0, NULL } > }; > > > PyMODINIT_FUNC modgl(void) I can't see how you were able to import the module. For "import modgl" to work, your initialisation function should be called "initmodgl". > { > (void) Py_InitModule("modgl", modglMethods); > }; > > You are writing an extension, not embedding Python. You don't need a main(). Lose it. > int > main(int argc, char *argv[]) > { > /* Pass argv[0] to the Python interpreter */ > Py_SetProgramName(argv[0]); > > /* Initialize the Python interpreter. Required. */ > Py_Initialize(); > > /* Add a static module */ > initmodgl(); > return 0; > }; Below is a cutdown version of your module, that returns a value so that you can see that it is working. You might like to use that as a base. Here it is working: |>>> import modgl |>>> modgl.glVertex4f(1, 2, 3, 4) 10.0 |>>> modgl.glVertex4f(1, 2, "three", 4) Traceback (most recent call last): File "", line 1, in ? TypeError: a float is required |>>> HTH, John 8<--- #include static PyObject * _wrap_glVertex4f(PyObject *self, PyObject *args) { PyObject *resultobj = NULL; float arg1, arg2, arg3, arg4; if(!PyArg_ParseTuple(args,"ffff:glVertex4f",&arg1,&arg2,&arg3,&arg4)) goto fail; /* glVertex4f(arg1,arg2,arg3,arg4); */ /* Py_INCREF(Py_None); resultobj = Py_None; */ resultobj = Py_BuildValue("d", (double)(arg1 + arg2 + arg3 + arg4)); return resultobj; fail: return NULL; }; static PyMethodDef modglMethods[] = { { (char *)"glVertex4f", _wrap_glVertex4f, METH_VARARGS, NULL}, { NULL, NULL, 0, NULL } }; PyMODINIT_FUNC initmodgl(void) { (void) Py_InitModule("modgl", modglMethods); }; 8<--- From samschul at pacbell.net Sat Jun 3 05:38:41 2006 From: samschul at pacbell.net (sam) Date: 2 Jun 2006 20:38:41 -0700 Subject: Seg fault in python extension module References: <4480F004.7000602@lexicon.net> Message-ID: <1149305921.145967.248740@i39g2000cwa.googlegroups.com> I recommend that you also replace the NULL after the METH_VARARGS with a valid documentations string such as: static PyMethodDef modglMethods[] = { { (char *)"glVertex4f", _wrap_glVertex4f, METH_VARARGS, "My Doc String"}, { NULL, NULL, 0, NULL } }; Sam Schulenburg From sjmachin at lexicon.net Sat Jun 3 05:56:35 2006 From: sjmachin at lexicon.net (John Machin) Date: Sat, 03 Jun 2006 13:56:35 +1000 Subject: Seg fault in python extension module In-Reply-To: <1149305921.145967.248740@i39g2000cwa.googlegroups.com> References: <4480F004.7000602@lexicon.net> <1149305921.145967.248740@i39g2000cwa.googlegroups.com> Message-ID: <44810873.3050200@lexicon.net> On 3/06/2006 1:38 PM, sam wrote: > I recommend that you also replace the NULL after the METH_VARARGS with > a valid documentations string such as: > > static PyMethodDef modglMethods[] = > { > { (char *)"glVertex4f", _wrap_glVertex4f, METH_VARARGS, "My > Doc String"}, > { NULL, NULL, 0, NULL } > > }; > Lack of one is unlikely to have anything to do with the OP's segfault. |>>> repr(modgl.glVertex4f.__doc__) 'None' |>>> As to style, etiquette, and good citizenship in module extension writing, it might be better to give him some references, rather than mention just one point. Cheers, John From samschul at pacbell.net Sat Jun 3 06:40:55 2006 From: samschul at pacbell.net (sam) Date: 2 Jun 2006 21:40:55 -0700 Subject: Seg fault in python extension module In-Reply-To: <44810873.3050200@lexicon.net> References: <4480F004.7000602@lexicon.net> <1149305921.145967.248740@i39g2000cwa.googlegroups.com> <44810873.3050200@lexicon.net> Message-ID: <1149309655.287866.10380@i40g2000cwc.googlegroups.com> Sorry, From MethodObject.h the 4th parameter is usually documented as having a NULL, but is intended to be used for a documentation string that will be available to the user under the various GUI IDE's such as IDLE or PyWin32. I just wanted to point that out.. struct PyMethodDef { const char *ml_name; /* The name of the built-in function/method */ PyCFunction ml_meth; /* The C function that implements it */ int ml_flags; /* Combination of METH_xxx flags, which mostly describe the args expected by the C func */ const char *ml_doc; /* The __doc__ attribute, or NULL */ }; Sam Schulenburg John Machin wrote: > On 3/06/2006 1:38 PM, sam wrote: > > I recommend that you also replace the NULL after the METH_VARARGS with > > a valid documentations string such as: > > > > static PyMethodDef modglMethods[] = > > { > > { (char *)"glVertex4f", _wrap_glVertex4f, METH_VARARGS, "My > > Doc String"}, > > { NULL, NULL, 0, NULL } > > > > }; > > > > Lack of one is unlikely to have anything to do with the OP's segfault. > > |>>> repr(modgl.glVertex4f.__doc__) > 'None' > |>>> > > As to style, etiquette, and good citizenship in module extension > writing, it might be better to give him some references, rather than > mention just one point. > > Cheers, > John From faulkner612 at comcast.net Sat Jun 3 02:09:24 2006 From: faulkner612 at comcast.net (faulkner) Date: 2 Jun 2006 17:09:24 -0700 Subject: do you have a local copy of Lython? Message-ID: <1149293364.597445.302600@y43g2000cwc.googlegroups.com> # Lython = Miles Egan's Lisp->Python compiler. The usual place throws a 404, and when I tried the email address in whois the server threw an error. I've asked around on a few forums, and somebody on irc.efnet.org/python suggested posting here. If you have a saved copy, please email it to me or link me to a working download. Thanks for your time, faulkner From gh at ghaering.de Sat Jun 3 02:34:31 2006 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sat, 03 Jun 2006 02:34:31 +0200 Subject: [ANNOUNCE] pyPgSQL 2.5 released Message-ID: <4480D917.7010405@ghaering.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello, the last pyPgSQL release was in July 2003. Now, after a much too long time I went through all items in the bugtracker and created a release. pyPgSQL is a Python database adapter for PostgreSQL databases. Its homepage is at http://pypgsql.sf.net/. Downloads are available here: http://sourceforge.net/project/showfiles.php?group_id=16528&package_id=20458&release_id=421992 There is a source package and Windows binaries for Python 2.4. The Windows binaries are dynamically linked this time, so you will need a PostgreSQL client library installation to make sure the DLLs are found. It's probably easiest to just include the PostgreSQL bin and lib directory in your PATH. Attached is a ChangeLog. - -- Gerhard -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFEgNkXdIO4ozGCH14RAgqlAJ9nNNGM1cTzMK804tV3ItOlDBcuBQCfYvQR GFaIhZnChH8ORdW7qMHKJMA= =K3Y4 -----END PGP SIGNATURE----- -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: Announce URL: From micklee74 at hotmail.com Sat Jun 3 03:30:30 2006 From: micklee74 at hotmail.com (micklee74 at hotmail.com) Date: 2 Jun 2006 18:30:30 -0700 Subject: check for dictionary keys Message-ID: <1149298230.864123.8320@u72g2000cwu.googlegroups.com> hi in my code, i use dict(a) to make to "a" into a dictionary , "a" comes from user input, so my program does not know in the first place. Then say , it becomes a = { '-A' : 'value1' , '-B' : "value2" , "-C" : "value3" , '-D' : 'value4' } somewhere next in my code, i will check for these..: 1) -A and -B cannot exist together 2) -A and -C cannot exist together 3) -A and -B and -D cannot exist together 4) and lots of other combinations to check for.... how can i efficiently check for the above? At first as i do simple checks , i use if and else. But as i began to check for more combinatoiuns, it gets messy.... thanks. From faulkner612 at comcast.net Sat Jun 3 03:43:03 2006 From: faulkner612 at comcast.net (faulkner) Date: 2 Jun 2006 18:43:03 -0700 Subject: check for dictionary keys In-Reply-To: <1149298230.864123.8320@u72g2000cwu.googlegroups.com> References: <1149298230.864123.8320@u72g2000cwu.googlegroups.com> Message-ID: <1149298983.720797.8460@i39g2000cwa.googlegroups.com> def all(s): for x in s: if not x: return False return True bad_combos = [['-A', '-B'], ['-A', '-C'], ...] for bad_combo in bad_combos: assert not all([bad_elem in a for bad_elem in bad_combo]) micklee74 at hotmail.com wrote: > hi > in my code, i use dict(a) to make to "a" into a dictionary , "a" comes > from user input, so my program does not know in the first place. Then > say , it becomes > > a = { '-A' : 'value1' , '-B' : "value2" , "-C" : "value3" , '-D' : > 'value4' } > > somewhere next in my code, i will check for these..: > > 1) -A and -B cannot exist together > 2) -A and -C cannot exist together > 3) -A and -B and -D cannot exist together > 4) and lots of other combinations to check for.... > > how can i efficiently check for the above? At first as i do simple > checks , i use if and else. > But as i began to check for more combinatoiuns, it gets messy.... > > thanks. From bdesth.quelquechose at free.quelquepart.fr Mon Jun 5 14:46:33 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 05 Jun 2006 14:46:33 +0200 Subject: check for dictionary keys In-Reply-To: <1149298230.864123.8320@u72g2000cwu.googlegroups.com> References: <1149298230.864123.8320@u72g2000cwu.googlegroups.com> Message-ID: <4483f80a$0$27349$626a54ce@news.free.fr> micklee74 at hotmail.com a ?crit : > hi > in my code, i use dict(a) to make to "a" into a dictionary , "a" comes > from user input, so my program does not know in the first place. Then > say , it becomes > > a = { '-A' : 'value1' , '-B' : "value2" , "-C" : "value3" , '-D' : > 'value4' } > > somewhere next in my code, i will check for these..: > > 1) -A and -B cannot exist together > 2) -A and -C cannot exist together > 3) -A and -B and -D cannot exist together > 4) and lots of other combinations to check for.... Looks like an option parser... If so, there's all you need in the standard lib (look for the optparse module). > > how can i efficiently check for the above? At first as i do simple > checks , i use if and else. > But as i began to check for more combinatoiuns, it gets messy.... First : use boolean logic (truth table, Kernaugh diagram, etc) to simplify things. As an example, rule #3 is useless - it's a subset of rule #1 (-A and -B and -D implies -A and -B). This should greatly reduce the number of needed tests. Then, write a simple rule system describing either valid inputs or invalid inputs (preferably the smallest set !-). FWIW, it can be as simple as a list of lambdas/error messages pairs, with lambdas being predicate taking dict keys as params: _RULES = [ (lambda keys : '-A' in keys and '-B' in keys, "can't have both options -A and -B"), (lambda keys : '-A' in keys and '-C' in keys, "can't have both options -A and -C"), # etc... ] def validate(options, rules): keys = options.keys() for predicate, message in rules: if not predicate(keys): raise ValueError(message) From sjmachin at lexicon.net Tue Jun 6 03:10:06 2006 From: sjmachin at lexicon.net (John Machin) Date: Tue, 06 Jun 2006 11:10:06 +1000 Subject: check for dictionary keys In-Reply-To: <4483f80a$0$27349$626a54ce@news.free.fr> References: <1149298230.864123.8320@u72g2000cwu.googlegroups.com> <4483f80a$0$27349$626a54ce@news.free.fr> Message-ID: <4484d5ee$1@news.eftel.com> On 5/06/2006 10:46 PM, Bruno Desthuilliers wrote: > micklee74 at hotmail.com a ?crit : >> hi >> in my code, i use dict(a) to make to "a" into a dictionary , "a" comes >> from user input, so my program does not know in the first place. Then >> say , it becomes >> >> a = { '-A' : 'value1' , '-B' : "value2" , "-C" : "value3" , '-D' : >> 'value4' } >> >> somewhere next in my code, i will check for these..: >> >> 1) -A and -B cannot exist together >> 2) -A and -C cannot exist together >> 3) -A and -B and -D cannot exist together >> 4) and lots of other combinations to check for.... > > Looks like an option parser... If so, there's all you need in the > standard lib (look for the optparse module). > >> >> how can i efficiently check for the above? At first as i do simple >> checks , i use if and else. >> But as i began to check for more combinatoiuns, it gets messy.... > > First : use boolean logic (truth table, Kernaugh diagram, etc) to > simplify things. As an example, rule #3 is useless - it's a subset of > rule #1 (-A and -B and -D implies -A and -B). This should greatly reduce > the number of needed tests. Good idea, but doesn't scale well. Simple code can weed out redundant rules, including any accidental duplicates that may creep into a long list. See code listing at end. > > Then, write a simple rule system describing either valid inputs or > invalid inputs (preferably the smallest set !-). FWIW, it can be as > simple as a list of lambdas/error messages pairs, with lambdas being > predicate taking dict keys as params: > > > _RULES = [ > (lambda keys : '-A' in keys and '-B' in keys, > "can't have both options -A and -B"), > (lambda keys : '-A' in keys and '-C' in keys, > "can't have both options -A and -C"), > # etc... > ] > The evil HR director won't let the PHB pay me on a per LOC basis, so I've had to come up with a compact table-driven approach :-) > def validate(options, rules): > keys = options.keys() > for predicate, message in rules: > if not predicate(keys): > raise ValueError(message) Cheers, John C:\junk>type option_combos.py bad_combos = ['ABD', 'AC', 'AB', 'CA'] def rule_compaction(bc_list, verbose=False): # The next few lines are admittedly oldfashioned :-) bc_sets = [set(x) for x in bc_list] deco = [(len(y), y) for y in bc_sets] deco.sort() bc_sets = [z[1] for z in deco] del deco if verbose: print "bc_sets #1:", bc_sets for k in xrange(len(bc_sets)-1, 0, -1): candidate = bc_sets[k] for ko in bc_sets[:k]: if ko <= candidate: if verbose: print candidate, "knocked out by", ko del bc_sets[k] break if verbose: print "bc_sets #2:", bc_sets return bc_sets option_rules = rule_compaction(bad_combos, verbose=True) def combo_disallowed_by(opt_set, rules): for rule in rules: if opt_set >= rule: return rule return None # redundantly, for emphasis if __name__ == "__main__": import sys for opt_string in sys.argv[1:]: failer = combo_disallowed_by(set(opt_string), option_rules) if failer: print repr(opt_string), "disallowed by", failer else: print repr(opt_string), "is OK" === a test === C:\junk>option_combos.py A AB AC AD BC ABD ABX XBA BX bc_sets #1: [set(['A', 'C']), set(['A', 'B']), set(['A', 'C']), set(['A', 'B', 'D'])] set(['A', 'B', 'D']) knocked out by set(['A', 'B']) set(['A', 'C']) knocked out by set(['A', 'C']) bc_sets #2: [set(['A', 'C']), set(['A', 'B'])] 'A' is OK 'AB' disallowed by set(['A', 'B']) 'AC' disallowed by set(['A', 'C']) 'AD' is OK 'BC' is OK 'ABD' disallowed by set(['A', 'B']) 'ABX' disallowed by set(['A', 'B']) 'XBA' disallowed by set(['A', 'B']) 'BX' is OK === the end === From onurb at xiludom.gro Tue Jun 6 12:38:36 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 06 Jun 2006 12:38:36 +0200 Subject: check for dictionary keys In-Reply-To: <4484d5ee$1@news.eftel.com> References: <1149298230.864123.8320@u72g2000cwu.googlegroups.com> <4483f80a$0$27349$626a54ce@news.free.fr> <4484d5ee$1@news.eftel.com> Message-ID: <44855b2c$0$10988$626a54ce@news.free.fr> John Machin wrote: > On 5/06/2006 10:46 PM, Bruno Desthuilliers wrote: > >> micklee74 at hotmail.com a ?crit : >> >>> hi >>> in my code, i use dict(a) to make to "a" into a dictionary , "a" comes >>> from user input, so my program does not know in the first place. Then >>> say , it becomes >>> >>> a = { '-A' : 'value1' , '-B' : "value2" , "-C" : "value3" , '-D' : >>> 'value4' } >>> >>> somewhere next in my code, i will check for these..: >>> >>> 1) -A and -B cannot exist together >>> 2) -A and -C cannot exist together >>> 3) -A and -B and -D cannot exist together >>> 4) and lots of other combinations to check for.... >> >> >> Looks like an option parser... If so, there's all you need in the >> standard lib (look for the optparse module). >> >>> >>> how can i efficiently check for the above? At first as i do simple >>> checks , i use if and else. >>> But as i began to check for more combinatoiuns, it gets messy.... >> >> >> First : use boolean logic (truth table, Kernaugh diagram, etc) to >> simplify things. As an example, rule #3 is useless - it's a subset of >> rule #1 (-A and -B and -D implies -A and -B). This should greatly >> reduce the number of needed tests. > > > Good idea, but doesn't scale well. Does it need to scale ? If there are lot of rules and frequently changing, yes, automating the process will be a good idea - but if it's about a program options, just using one's brain might be enough. At least it forces one to think about what's going on... > Simple code can weed out redundant > rules, Simple code can weed out redundant *simple* rules !-) (snip) >> Then, write a simple rule system describing either valid inputs or >> invalid inputs (preferably the smallest set !-). FWIW, it can be as >> simple as a list of lambdas/error messages pairs, with lambdas being >> predicate taking dict keys as params: >> >> >> _RULES = [ >> (lambda keys : '-A' in keys and '-B' in keys, >> "can't have both options -A and -B"), >> (lambda keys : '-A' in keys and '-C' in keys, >> "can't have both options -A and -C"), >> # etc... >> ] >> > > The evil HR director won't let the PHB pay me on a per LOC basis, so > I've had to come up with a compact table-driven approach :-) I'm my own evil HR director and PHB !-) Don't like table-driven programming, John ? This solution takes very few lines, and while it's surely not a full-blown rule engine, it's at least reasonably flexible. (Not to say it's better than yours - it's of course a matter of effective use case). >> def validate(options, rules): >> keys = options.keys() >> for predicate, message in rules: >> if not predicate(keys): >> raise ValueError(message) > > > > C:\junk>type option_combos.py > bad_combos = ['ABD', 'AC', 'AB', 'CA'] > > def rule_compaction(bc_list, verbose=False): > # The next few lines are admittedly oldfashioned :-) > bc_sets = [set(x) for x in bc_list] > deco = [(len(y), y) for y in bc_sets] > deco.sort() > bc_sets = [z[1] for z in deco] > del deco > if verbose: > print "bc_sets #1:", bc_sets > for k in xrange(len(bc_sets)-1, 0, -1): > candidate = bc_sets[k] > for ko in bc_sets[:k]: > if ko <= candidate: > if verbose: > print candidate, "knocked out by", ko > del bc_sets[k] > break > if verbose: > print "bc_sets #2:", bc_sets > return bc_sets > Nice code - but how does it handle more complex predicates ? Seems you can only deal with 'and' rules here. "Doesn't scale well", you said ?-) (snip) -- 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 Tue Jun 6 13:27:53 2006 From: sjmachin at lexicon.net (John Machin) Date: Tue, 06 Jun 2006 21:27:53 +1000 Subject: check for dictionary keys In-Reply-To: <44855b2c$0$10988$626a54ce@news.free.fr> References: <1149298230.864123.8320@u72g2000cwu.googlegroups.com> <4483f80a$0$27349$626a54ce@news.free.fr> <4484d5ee$1@news.eftel.com> <44855b2c$0$10988$626a54ce@news.free.fr> Message-ID: <448566b9@news.eftel.com> On 6/06/2006 8:38 PM, bruno at modulix wrote: > John Machin wrote: >> On 5/06/2006 10:46 PM, Bruno Desthuilliers wrote: >> >>> micklee74 at hotmail.com a ?crit : >>> >>>> hi >>>> in my code, i use dict(a) to make to "a" into a dictionary , "a" comes >>>> from user input, so my program does not know in the first place. Then >>>> say , it becomes >>>> >>>> a = { '-A' : 'value1' , '-B' : "value2" , "-C" : "value3" , '-D' : >>>> 'value4' } >>>> >>>> somewhere next in my code, i will check for these..: >>>> >>>> 1) -A and -B cannot exist together >>>> 2) -A and -C cannot exist together >>>> 3) -A and -B and -D cannot exist together >>>> 4) and lots of other combinations to check for.... >>> >>> Looks like an option parser... If so, there's all you need in the >>> standard lib (look for the optparse module). >>> >>>> how can i efficiently check for the above? At first as i do simple >>>> checks , i use if and else. >>>> But as i began to check for more combinatoiuns, it gets messy.... >>> >>> First : use boolean logic (truth table, Kernaugh diagram, etc) to >>> simplify things. As an example, rule #3 is useless - it's a subset of >>> rule #1 (-A and -B and -D implies -A and -B). This should greatly >>> reduce the number of needed tests. >> >> Good idea, but doesn't scale well. > > Does it need to scale ? If there are lot of rules and frequently > changing, yes, automating the process will be a good idea - but if it's > about a program options, just using one's brain might be enough. At > least it forces one to think about what's going on... > >> Simple code can weed out redundant >> rules, > > Simple code can weed out redundant *simple* rules !-) > > (snip) > >>> Then, write a simple rule system describing either valid inputs or >>> invalid inputs (preferably the smallest set !-). FWIW, it can be as >>> simple as a list of lambdas/error messages pairs, with lambdas being >>> predicate taking dict keys as params: >>> >>> >>> _RULES = [ >>> (lambda keys : '-A' in keys and '-B' in keys, >>> "can't have both options -A and -B"), >>> (lambda keys : '-A' in keys and '-C' in keys, >>> "can't have both options -A and -C"), >>> # etc... >>> ] >>> >> The evil HR director won't let the PHB pay me on a per LOC basis, so >> I've had to come up with a compact table-driven approach :-) > > I'm my own evil HR director and PHB !-) You must have some interesting conversations with yourself !-) > > Don't like table-driven programming, John ? I love table-driven programming. You seem to misunderstand; In this case the "bad combos" list *is* the table. > > This solution takes very few lines, and while it's surely not a > full-blown rule engine, it's at least reasonably flexible. > > (Not to say it's better than yours - it's of course a matter of > effective use case). > [snip] > > Nice code - but how does it handle more complex predicates ? Seems you > can only deal with 'and' rules here. More complex predicates are not in the OP's spec ... this is a defence I learned from somebody in this newsgroup recently :-) > "Doesn't scale well", you > said ?-) I understand 'scale' to relate to size, not to complexity. Cheers, John From alikakakhel at yahoo.com Sat Jun 3 05:40:00 2006 From: alikakakhel at yahoo.com (greenflame) Date: 2 Jun 2006 20:40:00 -0700 Subject: how to erase a variable Message-ID: <1149306000.615590.30020@c74g2000cwc.googlegroups.com> Is there a way to get rid of a variable as though it never existed? I know this sounds very basic but I have not come across any such methods. Also is the fact that I will have a bunch of extra variables just haning around because my use for them is over a bad thing? I will likely have on the order of 10 to 50 or so of these for the particular program I an working on at the moment. From sjmachin at lexicon.net Sat Jun 3 05:44:11 2006 From: sjmachin at lexicon.net (John Machin) Date: 2 Jun 2006 20:44:11 -0700 Subject: how to erase a variable In-Reply-To: <1149306000.615590.30020@c74g2000cwc.googlegroups.com> References: <1149306000.615590.30020@c74g2000cwc.googlegroups.com> Message-ID: <1149306251.073558.274980@i39g2000cwa.googlegroups.com> greenflame wrote: > Is there a way to get rid of a variable as though it never existed? I > know this sounds very basic but I have not come across any such > methods. Also is the fact that I will have a bunch of extra variables > just haning around because my use for them is over a bad thing? I will > likely have on the order of 10 to 50 or so of these for the particular > program I an working on at the moment. del rubbish, garbage, junk, unwanted_stuff From bignose+hates-spam at benfinney.id.au Sat Jun 3 06:59:15 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 03 Jun 2006 14:59:15 +1000 Subject: how to erase a variable References: <1149306000.615590.30020@c74g2000cwc.googlegroups.com> Message-ID: <87k67yygv0.fsf@benfinney.id.au> "greenflame" writes: > Is there a way to get rid of a variable as though it never existed? I > know this sounds very basic but I have not come across any such > methods. You can use the 'del' statement to delete a name. > Also is the fact that I will have a bunch of extra variables just > haning around because my use for them is over a bad thing? I will > likely have on the order of 10 to 50 or so of these for the > particular program I an working on at the moment. It doesn't cause the computer any grief to have extra objects; they'll eventually be cleaned up by garbage collection anyway. That said, it sounds like your program is not modular enough, which is a burden on the *programmer* to need to keep so many items in their head at once. It's far better to divide your program into discrete functional units, and write each conceptual step as a function. By dividing your program into functional modules (whether they be functions, classes with methods, or separate program modules) each unit of functionality has a limited scope, and the variables are local and get cleaned up after the function ends. This greatly aids the person reading the program: they have fewer things to concentrate on at any point in your program. -- \ "For every complex problem, there is a solution that is simple, | `\ neat, and wrong." -- Henry L. Mencken | _o__) | Ben Finney From alikakakhel at yahoo.com Sat Jun 3 23:14:36 2006 From: alikakakhel at yahoo.com (greenflame) Date: 3 Jun 2006 14:14:36 -0700 Subject: how to erase a variable In-Reply-To: References: <1149306000.615590.30020@c74g2000cwc.googlegroups.com> Message-ID: <1149369276.885120.230110@c74g2000cwc.googlegroups.com> Ok thanks all! From klaus at seistrup.dk Sat Jun 3 10:36:43 2006 From: klaus at seistrup.dk (Klaus Alexander Seistrup) Date: Sat, 3 Jun 2006 08:36:43 +0000 (UTC) Subject: Missing unicode data? Message-ID: Hi group, I just came across the following exception: #v+ $ python Python 2.4.2 (#2, Sep 30 2005, 21:19:01) [GCC 4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu8)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import unicodedata >>> u'\N{LATIN LETTER SMALL CAPITAL BARRED B}' UnicodeDecodeError: 'unicodeescape' codec can't decode bytes in position 0-38: unknown Unicode character name >>> unicodedata.name(u'\u1d03') Traceback (most recent call last): File "", line 1, in ? ValueError: no such name >>> ^D $ #v- When checking unicodedata.name() against each uchar in the file /usr/share/unidata/UnicodeData-4.0.1d1b.txt that came with the console-data package on my Ubuntu Linux installation a total of 1226 unicode characters seems to be missing from the unicodedata module (2477 missing characters when checking against the latest database from unicode.org?). Is this a deliberate omission? Cheers, Klaus. ?) http://www.unicode.org/Public/UNIDATA/UnicodeData.txt -- Klaus Alexander Seistrup SubZeroNet, Copenhagen, Denmark http://magnetic-ink.dk/ From fredrik at pythonware.com Sat Jun 3 11:16:39 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 03 Jun 2006 11:16:39 +0200 Subject: Missing unicode data? In-Reply-To: References: Message-ID: Klaus Alexander Seistrup wrote: > When checking unicodedata.name() against each uchar in the file > /usr/share/unidata/UnicodeData-4.0.1d1b.txt that came with the > console-data package on my Ubuntu Linux installation a total of > 1226 unicode characters seems to be missing from the unicodedata > module (2477 missing characters when checking against the latest > database from unicode.org?). Is this a deliberate omission? I'm pretty sure unicodename.name() doesn't look in the UnicodeData file on your machine, nor in the latest file from unicode.org. in other words, you get whatever version that was used to create the Unicode data set in your Python distribution. this is usually the version that was current when that Python version was originally released (i.e. in your case, when 2.4 was released). iirc, 2.4 uses Unicode 3.2, and 2.5 uses Unicode 4.1. to update, use the tools under Tools/unicode. From klaus at seistrup.dk Sat Jun 3 13:44:55 2006 From: klaus at seistrup.dk (Klaus Alexander Seistrup) Date: Sat, 3 Jun 2006 11:44:55 +0000 (UTC) Subject: Missing unicode data? References: Message-ID: Fredrik Lundh skrev: > I'm pretty sure unicodename.name() doesn't look in the Unicode- > Data file on your machine, nor in the latest file from unicode.org. I am pretty sure of that, too. I was only using those files as a reference against the unicode data that comes with my python interpreter. > in other words, you get whatever version that was used to create > the Unicode data set in your Python distribution. I see. > iirc, 2.4 uses Unicode 3.2, and 2.5 uses Unicode 4.1. to update, > use the tools under Tools/unicode. Thanks for the hint. Mvh, -- Klaus Alexander Seistrup SubZeroNet, Copenhagen, Denmark http://magnetic-ink.dk/ From iamkey9 at 126.com Sat Jun 3 11:30:08 2006 From: iamkey9 at 126.com (key9) Date: Sat, 3 Jun 2006 17:30:08 +0800 Subject: can python be a "shell" of c++ program? Message-ID: Hi all I have some data to process, whith complex mechanism,I put these process mechanism as plugins. and design lots of classes to abstract data themselves. but the question is how to drive them work together. That cause too much jobs: I should write UI,parser......almost a completed system. The problem is I don't know what these processed data will finally needed to display to user. maybe this , may be that, these can not know on design time. what I need is on outside of program, I can use some interface to get these data what I want , or push back data, or told program to recalculate it. can I have a way to drive c++ code use this script-like way ? thank you very much key9 From spiralx at gmail.com Sat Jun 3 18:00:58 2006 From: spiralx at gmail.com (James) Date: Sat, 3 Jun 2006 17:00:58 +0100 Subject: can python be a "shell" of c++ program? In-Reply-To: References: Message-ID: <7ee3dcd80606030900p7ad62ad0i6e06f9ec1fba2f23@mail.gmail.com> Yes you can, although it might be a fair bit of work depending on the complexity of your codebase. Basically you would need to write Python extensions to expose your C++ classes as Python modules, using SWIG or the Python extension code in the Boost C++ libraries. You'd then embed an interpreter in your program which would allow you to use Python code within it - either from a script or individual commands. It's a fairly common use of Python :) James On 03/06/06, key9 wrote: > Hi all > > I have some data to process, whith complex mechanism,I put these process > mechanism as plugins. > and design lots of classes to abstract data themselves. > > but the question is how to drive them work together. > > That cause too much jobs: I should write UI,parser......almost a completed > system. > > The problem is I don't know what these processed data will finally needed to > display to user. > maybe this , may be that, these can not know on design time. > > what I need is on outside of program, > I can use some interface to get these data what I want , or push back data, > or told program to recalculate it. > > > can I have a way to drive c++ code use this script-like way ? > > > thank you very much From tomerfiliba at gmail.com Sat Jun 3 16:10:23 2006 From: tomerfiliba at gmail.com (gangesmaster) Date: 3 Jun 2006 07:10:23 -0700 Subject: carshing the interpreter in two lines Message-ID: <1149343823.789918.210110@h76g2000cwa.googlegroups.com> the following (random) code crashes my interpreter (python 2.4.3/winxp): from types import CodeType as code exec code(0, 5, 8, 0, "hello moshe", (), (), (), "", "", 0, "") i would expect the interpreter to do some verifying, at least for sanity (valid opcodes, correct stack size, etc.) before executing artbitrary code... after all, it was the BDFL who said """I'm not saying it's uncrashable. I'm saying that if you crash it, it's a bug unless proven harebrained.""" -tomer From samschul at pacbell.net Sat Jun 3 18:07:34 2006 From: samschul at pacbell.net (sam) Date: 3 Jun 2006 09:07:34 -0700 Subject: carshing the interpreter in two lines In-Reply-To: <1149343823.789918.210110@h76g2000cwa.googlegroups.com> References: <1149343823.789918.210110@h76g2000cwa.googlegroups.com> Message-ID: <1149350854.072412.263920@f6g2000cwb.googlegroups.com> tomer: It is my opinion that you would loose performance if the Python interpreter had the additional task of verifying byte code. It might be more appropriate to have a preprocessor that did the verifying as it compiled the byte code. Sam Schulenburg gangesmaster wrote: > the following (random) code crashes my interpreter > (python 2.4.3/winxp): > > from types import CodeType as code > exec code(0, 5, 8, 0, "hello moshe", (), (), (), "", "", 0, "") > > i would expect the interpreter to do some verifying, at least for > sanity (valid opcodes, correct stack size, etc.) before executing > artbitrary code... after all, it was the BDFL who said """I'm not > saying it's uncrashable. I'm saying that if you crash it, it's a > bug unless proven harebrained.""" > > > -tomer From mwilson-to at sympatico.ca Sat Jun 3 20:11:54 2006 From: mwilson-to at sympatico.ca (Mel Wilson) Date: Sat, 03 Jun 2006 14:11:54 -0400 Subject: carshing the interpreter in two lines In-Reply-To: <1149350854.072412.263920@f6g2000cwb.googlegroups.com> References: <1149343823.789918.210110@h76g2000cwa.googlegroups.com> <1149350854.072412.263920@f6g2000cwb.googlegroups.com> Message-ID: sam wrote: > tomer: > > It is my opinion that you would loose performance if the Python > interpreter had the additional task of verifying byte code. It might be > more appropriate to have a preprocessor that did the verifying as it > compiled the byte code. Possibly. A good book on the topic is Douglas Hofstadter's _Goedel, Escher, Bach: an Eternal Golden Braid_. Particularly starting from the chapter "Contracrostipunctus". Cheers, Mel. > Sam Schulenburg > > gangesmaster wrote: >> the following (random) code crashes my interpreter >> (python 2.4.3/winxp): >> >> from types import CodeType as code >> exec code(0, 5, 8, 0, "hello moshe", (), (), (), "", "", 0, "") >> >> i would expect the interpreter to do some verifying, at least for >> sanity (valid opcodes, correct stack size, etc.) before executing >> artbitrary code... after all, it was the BDFL who said """I'm not >> saying it's uncrashable. I'm saying that if you crash it, it's a >> bug unless proven harebrained.""" >> >> >> -tomer > From samschul at pacbell.net Sat Jun 3 22:41:01 2006 From: samschul at pacbell.net (sam) Date: 3 Jun 2006 13:41:01 -0700 Subject: carshing the interpreter in two lines In-Reply-To: References: <1149343823.789918.210110@h76g2000cwa.googlegroups.com> <1149350854.072412.263920@f6g2000cwb.googlegroups.com> Message-ID: <1149367261.176919.134090@y43g2000cwc.googlegroups.com> Mel: Wow that book brings back memories. I scanned my copy to review the subject covered, and came to the conclusion that mind reading algorithms are the answer. Sam Schulenburg Mel Wilson wrote: > sam wrote: > > tomer: > > > > It is my opinion that you would loose performance if the Python > > interpreter had the additional task of verifying byte code. It might be > > more appropriate to have a preprocessor that did the verifying as it > > compiled the byte code. > > Possibly. A good book on the topic is Douglas Hofstadter's > _Goedel, Escher, Bach: an Eternal Golden Braid_. > > Particularly starting from the chapter "Contracrostipunctus". > > Cheers, Mel. > > > > > Sam Schulenburg > > > > gangesmaster wrote: > >> the following (random) code crashes my interpreter > >> (python 2.4.3/winxp): > >> > >> from types import CodeType as code > >> exec code(0, 5, 8, 0, "hello moshe", (), (), (), "", "", 0, "") > >> > >> i would expect the interpreter to do some verifying, at least for > >> sanity (valid opcodes, correct stack size, etc.) before executing > >> artbitrary code... after all, it was the BDFL who said """I'm not > >> saying it's uncrashable. I'm saying that if you crash it, it's a > >> bug unless proven harebrained.""" > >> > >> > >> -tomer > > From mwilson-to at sympatico.ca Sun Jun 4 17:27:06 2006 From: mwilson-to at sympatico.ca (Mel Wilson) Date: Sun, 04 Jun 2006 11:27:06 -0400 Subject: carshing the interpreter in two lines In-Reply-To: <1149367261.176919.134090@y43g2000cwc.googlegroups.com> References: <1149343823.789918.210110@h76g2000cwa.googlegroups.com> <1149350854.072412.263920@f6g2000cwb.googlegroups.com> <1149367261.176919.134090@y43g2000cwc.googlegroups.com> Message-ID: sam wrote: > Mel: > Wow that book brings back memories. I scanned my copy to review the > subject covered, and came to the conclusion that mind reading > algorithms are the answer. > I gathered from somewhere (but not the index to Andrew Hodges' biography) that Turing was toying with an idea for "oracles", where a computation would be allowed to call out sometimes to a non-computational process to obtain some required result. Used maybe by interactive debugging programs. Cheers, Mel. > Mel Wilson wrote: [ ... ] >>Douglas Hofstadter's _Goedel, Escher, Bach: an Eternal Golden Braid_. [ ... ] >> "Contracrostipunctus". From aleax at mac.com Sat Jun 3 20:12:19 2006 From: aleax at mac.com (Alex Martelli) Date: Sat, 3 Jun 2006 11:12:19 -0700 Subject: carshing the interpreter in two lines References: <1149343823.789918.210110@h76g2000cwa.googlegroups.com> <1149350854.072412.263920@f6g2000cwb.googlegroups.com> Message-ID: <1hgcsal.x6phhi1i5nx0qN%aleax@mac.com> sam wrote: > tomer: > > It is my opinion that you would loose performance if the Python > interpreter had the additional task of verifying byte code. It might be > more appropriate to have a preprocessor that did the verifying as it > compiled the byte code. But in this case, there is no "compiled" -- just the code type's constructor: > > from types import CodeType as code > > exec code(0, 5, 8, 0, "hello moshe", (), (), (), "", "", 0, "") Yes, code() itself could do some sanity checking. But so could 'exec' -- it's never a particularly fast operation anyway... and most definitely NOT on the critical path of normal operations. I'd rather have "defense in depth", in this case. Alex From aahz at pythoncraft.com Sun Jun 4 18:53:18 2006 From: aahz at pythoncraft.com (Aahz) Date: 4 Jun 2006 09:53:18 -0700 Subject: carshing the interpreter in two lines References: <1149343823.789918.210110@h76g2000cwa.googlegroups.com> Message-ID: In article <1149343823.789918.210110 at h76g2000cwa.googlegroups.com>, gangesmaster wrote: > >the following (random) code crashes my interpreter >(python 2.4.3/winxp): > >from types import CodeType as code >exec code(0, 5, 8, 0, "hello moshe", (), (), (), "", "", 0, "") > >i would expect the interpreter to do some verifying, at least for >sanity (valid opcodes, correct stack size, etc.) before executing >artbitrary code... after all, it was the BDFL who said """I'm not >saying it's uncrashable. I'm saying that if you crash it, it's a >bug unless proven harebrained.""" IIRC, this has been discussed before and deemed harebrained. Check SF to see whether this specific case has been submitted previously and submit it if not. Then post to python-dev if it's a new bug and ask for a ruling on whether it's harebrained. -- 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 edreamleo at charter.net Sat Jun 3 16:24:06 2006 From: edreamleo at charter.net (Edward K. Ream) Date: Sat, 3 Jun 2006 09:24:06 -0500 Subject: Leo 4.4.1 beta 1 released Message-ID: Leo 4.4.1 beta 1 is now available at: http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 Leo is a text editor, data organizer, project manager and much more. See: http://webpages.charter.net/edreamleo/intro.html The highlights of Leo 4.4.1: ---------------------------- - A new colorizer plugin controlled by jEdit language description files. At present this plugin only reliably colors @language python code. - Multiple editors in Leo's body pane. - Search commands now support regex replace patterns: \1, \2, etc. - Support for external debuggers: see http://webpages.charter.net/edreamleo/debuggers.html - The scripting plugin now creates a Debug Script button. - Several new commands including run-unit-test, python-help and toggle-invisibles. - The help-for-command commands now contains information for almost all commands. - A new shortcut_button plugin. Links: ------ Leo: http://webpages.charter.net/edreamleo/front.html Home: http://sourceforge.net/projects/leo/ Download: http://sourceforge.net/project/showfiles.php?group_id=3458 CVS: http://leo.tigris.org/source/browse/leo/ Quotes: http://webpages.charter.net/edreamleo/testimonials.html -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From laurent.pointal at wanadoo.fr Sat Jun 3 18:29:51 2006 From: laurent.pointal at wanadoo.fr (Laurent Pointal) Date: Sat, 03 Jun 2006 18:29:51 +0200 Subject: ANN: PQRC - Python Quick Reference Card - v 0.55 Message-ID: <4481b8ff$0$19687$ba4acef3@news.orange.fr> [for those who dont read clp.announce] The Python Quick Reference Card (PQRC) aims to provide a printable quick reference documentation for the Python language and some of its main standard libraries (currently for Python 2.4). PQRC tries to group informations about same/similar subject to avoid searching in multiple places. It is published under a Creative Common [by nc sa] license. It is still a work in progress, but currently usable, you can get it at: http://www.limsi.fr/Individu/pointal/python/pqrc/ And I'll maintain a fixed URL at http://laurent.pointal.org/python/pqrc/ From kent at kentsjohnson.com Sun Jun 4 14:14:19 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Sun, 04 Jun 2006 08:14:19 -0400 Subject: ANN: PQRC - Python Quick Reference Card - v 0.55 In-Reply-To: <4481b8ff$0$19687$ba4acef3@news.orange.fr> References: <4481b8ff$0$19687$ba4acef3@news.orange.fr> Message-ID: <4482cd93$1_2@newspeer2.tds.net> Laurent Pointal wrote: > And I'll maintain a fixed URL at > > http://laurent.pointal.org/python/pqrc/ Broken at the moment. Kent From laurent.pointal at wanadoo.fr Sun Jun 4 20:33:07 2006 From: laurent.pointal at wanadoo.fr (Laurent Pointal) Date: Sun, 04 Jun 2006 20:33:07 +0200 Subject: ANN: PQRC - Python Quick Reference Card - v 0.55 References: <4481b8ff$0$19687$ba4acef3@news.orange.fr> <4482cd93$1_2@newspeer2.tds.net> Message-ID: <44832763$0$20143$ba4acef3@news.orange.fr> Kent Johnson wrote: > Laurent Pointal wrote: >> And I'll maintain a fixed URL at >> >> http://laurent.pointal.org/python/pqrc/ > > Broken at the moment. Its back. Its at my home ADSL, normally online, but my provider reset the connexion each 24h and its home maintained... the page contains only a link to the other URL which has the data and is beyond a larger bandwidth server. A+ Laurent. > > Kent From gene.tani at gmail.com Sun Jun 4 14:59:02 2006 From: gene.tani at gmail.com (gene tani) Date: 4 Jun 2006 05:59:02 -0700 Subject: ANN: PQRC - Python Quick Reference Card - v 0.55 In-Reply-To: <4481b8ff$0$19687$ba4acef3@news.orange.fr> References: <4481b8ff$0$19687$ba4acef3@news.orange.fr> Message-ID: <1149425942.073680.234250@u72g2000cwu.googlegroups.com> Laurent Pointal wrote: > [for those who dont read clp.announce] > > The Python Quick Reference Card (PQRC) aims to provide a printable quick > reference documentation for the Python language and some of its main > standard libraries (currently for Python 2.4). > > PQRC tries to group informations about same/similar subject to avoid > searching in multiple places. > very nice. There's a few others I've collected over the years. I havent found an OS X dashboard widget yet tho: http://rgruet.free.fr/#QuickRef http://infohost.nmt.edu/tcc/help/pubs/python22.pdf http://www.onlamp.com/python/excerpt/PythonPocketRef/examples/python.pdf http://diveintopython.org/appendix/abstracts.html http://www.yukoncollege.yk.ca/~ttopper/COMP118/rCheatSheet.html http://www.schacherer.de/frank/tech/tools/python.html http://www.experimentierkasten.de/python_php.pdf http://ferg.org/pyref/index.html http://projects.edgewall.com/python-sidebar/ http://jotsite.com/blogArchives/2006_03.php#000383 http://www.drweb.de/weblog/weblog/?p=571 http://www.petefreitag.com/item/455.cfm From artur_spruce at yahoo.com Mon Jun 5 13:29:36 2006 From: artur_spruce at yahoo.com (AdSR) Date: 5 Jun 2006 04:29:36 -0700 Subject: ANN: PQRC - Python Quick Reference Card - v 0.55 References: <4481b8ff$0$19687$ba4acef3@news.orange.fr> Message-ID: <1149506976.002410.207870@y43g2000cwc.googlegroups.com> Laurent Pointal wrote: > [for those who dont read clp.announce] > > The Python Quick Reference Card (PQRC) aims to provide a printable quick > reference documentation for the Python language and some of its main > standard libraries (currently for Python 2.4). > [etc.] Great job, Laurent! If this is version 0.55, I can't wait for 1.0. Keep up the good work. BTW, it would be great if something like this came with Python installation. No more sifting through library TOC/index, "where did I see this stuff" :) AdSR From andre.roberge at gmail.com Sat Jun 3 18:46:13 2006 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 3 Jun 2006 09:46:13 -0700 Subject: elementtree and inclusion of special characters Message-ID: <1149353173.530528.116170@f6g2000cwb.googlegroups.com> I'm using elementtree to process some html files, by building a tree, manipulating it, and writing it back. One problem I encounter is that elementtree converts some symbols in an unwanted way. For example, the symbol ">" is converted to ">". This is fine in html code, but not if the page includes some script like the example below The resulting code, with "a > 0" is not understood by the browser... Any suggestions as to how I can circumvent this problem in an easy way? Andr? From fredrik at pythonware.com Sat Jun 3 19:29:00 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 03 Jun 2006 19:29:00 +0200 Subject: elementtree and inclusion of special characters In-Reply-To: <1149353173.530528.116170@f6g2000cwb.googlegroups.com> References: <1149353173.530528.116170@f6g2000cwb.googlegroups.com> Message-ID: Andr? wrote: > I'm using elementtree to process some html files, by building a tree, > manipulating it, and writing it back. One problem I encounter is that > elementtree converts some symbols in an unwanted way. For example, the > symbol ">" is converted to ">". This is fine in html code, but not > if the page includes some script like the example below > > > > The resulting code, with "a > 0" is not understood by the browser... ET is an XML library, and an XHTML-aware browser has no problems dealing with that, but I assume you might want to support tag soup parsers like IE6 as well ;-) to write true HTML 4.0, you need a HTML serializer. there's a good one in Kid (though I don't know how hard it would be to use that one with a preexisting tree, rather than a Kid "event stream"). another alternative is the HTMLTree class in Ian Bicking's commentary application: http://svn.pythonpaste.org/Paste/apps/Commentary/trunk/commentary/dumbpath.py (you may have to tweak that module somewhat to be able to use it without elementtidy). From no-spam at no-spam-no-spam.com Sat Jun 3 19:38:44 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Sat, 03 Jun 2006 19:38:44 +0200 Subject: __builtins__.loglog - logging more pythonic, decent & scalable ? - Re: "No handlers could be found for logger xxx" Message-ID: As more and more python packages are starting to use the bloomy (Java-ish) 'logging' module in a mood of responsibility and as I am not overly happy with the current "thickener" style of usage, I want to put this comment and a alternative most simple default framework for discussion. Maybe there are more Python users which like to see that imported (managed) logging issue more down-to-earth and flexible ? ... Vinay Sajip wrote: > robert wrote: > >>some packages like paramiko use the logging. I get this messages: >>"No handlers could be found for logger xxx" on stderr >> >>Why is un-initialized logging allowed to chatter at all? > > You could invoke logging.basicConfig with a level of CRITICAL. This > will generally filter out logging messages. Meanwhile i looked on logging and its doc: The doc of for example basicConfig (promising to be quite simple/silent): "basicConfig( ) Does basic configuration for the logging system by creating a StreamHandler with a default Formatter and adding it to the root logger. The functions debug(), info(), warning(), error() and critical() will call basicConfig() automatically if no handlers are defined for the root logger. " => So far I don't get any idea what will happen after doing this. What is a StreamHandler? a "default Formatter"? CRITICAL? what is this default magic behavior? even if silent behavior is installed log(), debug() consume still a lot of execution time => I have to read the logging code anyway => for my needs i rendered dead the Logger() in app-init / dead the line in logging which chatters within my standard set of Python patches. I looked around a little more and think, that logging it is really a _FRAMEWORK_ - non-pythonic . a declarative monster. Meaning: too big the interface and too big its basic footprint. without a decent scaling. too loud. it takes lots of time until one understands the basics. even the simplest setup example has not less than 8 lines - strange "filehandlers" and "formatters" are going on - and it is a framework which does a lot of obscure things, its class collection reads more like an magic application only understandable by its immediate programmers - rather than a stdlib part. Its almost a Java-ish ego class bunch. Some wide spread packages like paramiko use it already - inside stdlib only cookielib so far. Yet, just for providing the option they are costly pre-importing almost the whole framework functionality (in memory, frozen apps etc.) and have considerable costs during execution (regarding my step-in debugging sessions: seems to do very very late dispatching). Python is still not an OS on its own but a programming language/library which should fit into OS'es. ( though they meanwhile put the CJK codecs etc. into the python core !? :-) ) Yes, one could use such functionality - but one does only in rarest cases. I did and do logging a lot, but always had quite simple paths. I'd usually still not go though that framework in almost all cases, because it would require many hours until I really know whats going magically in all kinds of cases. 99% of my app logging needs were and are fulfilled by a simple direct module function as simple as: def doLog(text,level,**kwattrs): # in case write to file or whatever ... and so I simply know really what will happen. Collecting all logs is also so easy with Python, that it could be _enabled_ by a much much simpler and pythonic one-function-framework: a empty log-hook function in the python __builtins__: ========================================================= def loglog(text, channel='default', level=0, **kwattrs): pass ========================================================= yet there could go any complex hierarchical channel names through that like channel="mypackage.mymodule.subtheme" or even multi-hierarchical channel classes/objects similar to exception-class-catching in addition to string-catching. Example: ========================================================= class MyLogChannelAA(MyLogChannelA, MyLogAspectXY) loglog(text, MyLogChannelAA, __debug__, lcls=locals() ) ========================================================= If that simple would be the recommended standard logging interface in Python, I think, really a significant fraction of Python programmers would first understand and than use ( call and consume ) it - and (decent) modules would not blow up the machine unconditionally just for a mere specialized option. For massive usage apps could shortcut THEMSELVES with bloomy names and level-constants like logdebug() logerror() .... (Recommendations at best - no more framework.) Still this would be flexible enough and a super-hierarchical obscure logger and handler collection as exposed by "logging" or any other alternative could still be hooked in, while no module which does logging has to PRE-IMPORT SUCH A FAT SPECIAL LOGGING FRAMEWORK. > Un-initialized logging chatters because in development environments, > it's useful to be able to spot misconfigured loggers. For production > use, set logging.raiseExceptions to 0 and logging should then be quiet. Think a potentially "misconfigured logger" is not a reason to chatter. If there is an error in setup you'd 99.99% get an exception. If you really totally forget to setup - you simply have forgotten as you can forget many things. If you really want log's you'll have 1000 chances as developer to see that there are no logs - and add the setup. My opinion: _By default_ logging should really * be totally silent * not import all the logging code and handler classes etc. (but only a minimal stub or do ** (see below)) * consume only minimum execution time: Consider a typical complex program: Hundreds and thousands of things have to be be set up and configured which are much more important than a debug logger. Yet not every imported library and every class yells because it was not used or not basicConfig'ed :-). The logging is not the center of the world. In 99% only the developer of a module uses/wants the log output. I see there were already other complaints about this chattering - and other people also wondered how to make it silent. -- In cookielib recently the logging initialization has been **virtualized => its not imported / necessary (in frozen apps) until the cookielib debugging was not really requested. Think thats a better/acceptable style of use and such guidline should be put at the top of the logging docs to complete/alternate the above 3 issues. That all maybe could be healed most easily by the proposed __builtin__.loglog in Python : not unconditional wiring to such a specific and fat package. -robert From mikeisgreat at gmail.com Sat Jun 3 20:05:23 2006 From: mikeisgreat at gmail.com (mikeisgreat at gmail.com) Date: 3 Jun 2006 11:05:23 -0700 Subject: restarting multiple instances of apache - newbie Q Message-ID: <1149357923.926548.96230@y43g2000cwc.googlegroups.com> hi all, i am new to python programming, so thanks for your patience in advance. I have a small script that I am working on that i want to restart multiple instances of apaches on our developers servers. We have about 25 developers each with their own apache. import sys, os try: file = open("users.dat", "r") except IOError, message: print >> sys.stderr, "File could not be opened:", message sys.exit( 1 ) fdata = file.xreadlines() for data in fdata: fields = data.split("_") # print "USER: " + fields[0] + " ADDRESS: " + fields[1].strip("\n") print '/etc/init.d/httpd_' + fields[0] + ' restart each users apache is named 'httpd_{user}' I am not sure how to do this cleanly other than in a shell script. I want to restart the apache and wait until complete to restart the next users apache. Any advice is appreciated .. again, thanks for your time. -mike From pmartin at snakecard.com Sat Jun 3 20:21:49 2006 From: pmartin at snakecard.com (pcm) Date: Sat, 03 Jun 2006 13:21:49 -0500 Subject: Python + WinCE + serial port Message-ID: <4481d342$0$21359$636a55ce@news.free.fr> Hi, Has anyone ever worked on a Python-WinCE-based program that involved serial port management ? Regards, Philippe From fuzzyman at gmail.com Sat Jun 3 20:49:27 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 3 Jun 2006 11:49:27 -0700 Subject: Python + WinCE + serial port In-Reply-To: <4481d342$0$21359$636a55ce@news.free.fr> References: <4481d342$0$21359$636a55ce@news.free.fr> Message-ID: <1149360567.824911.245750@c74g2000cwc.googlegroups.com> pcm wrote: > Hi, > > Has anyone ever worked on a Python-WinCE-based program that involved serial > port management ? > Because of the size of the runtime and the fragility of the GUI toolkits, there has been little serious development with PythonCE. (Little not none - and it's great to have Python available.) There is no built in support for the serial port in PythonCE (AFAIK). Your best bet is using ctypes (for which a PythonCE port has been done) and the microsoft API. Fuzzyman http://www.voidspace.org.uk/python/index.shtml > Regards, > > Philippe From pmartin at snakecard.com Sun Jun 4 11:47:36 2006 From: pmartin at snakecard.com (pcm) Date: Sun, 04 Jun 2006 04:47:36 -0500 Subject: Python + WinCE + serial port References: <4481d342$0$21359$636a55ce@news.free.fr> <1149360567.824911.245750@c74g2000cwc.googlegroups.com> Message-ID: <4482ac3c$0$12347$626a54ce@news.free.fr> Fuzzyman wrote: > > pcm wrote: >> Hi, >> >> Has anyone ever worked on a Python-WinCE-based program that involved >> serial port management ? >> > > Because of the size of the runtime and the fragility of the GUI > toolkits, there has been little serious development with PythonCE. > (Little not none - and it's great to have Python available.) > > There is no built in support for the serial port in PythonCE (AFAIK). > Your best bet is using ctypes (for which a PythonCE port has been done) > and the microsoft API. > > Fuzzyman > http://www.voidspace.org.uk/python/index.shtml > >> Regards, >> >> Philippe Thanks, does that mean that I need to write an extension to the WinCE API or is that built-into the Python package ? Regards, Philippe From fuzzyman at gmail.com Tue Jun 6 00:11:55 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 5 Jun 2006 15:11:55 -0700 Subject: Python + WinCE + serial port In-Reply-To: <4482ac3c$0$12347$626a54ce@news.free.fr> References: <4481d342$0$21359$636a55ce@news.free.fr> <1149360567.824911.245750@c74g2000cwc.googlegroups.com> <4482ac3c$0$12347$626a54ce@news.free.fr> Message-ID: <1149545515.102850.272920@j55g2000cwa.googlegroups.com> pcm wrote: > Fuzzyman wrote: > > > > > pcm wrote: > >> Hi, > >> > >> Has anyone ever worked on a Python-WinCE-based program that involved > >> serial port management ? > >> > > > > Because of the size of the runtime and the fragility of the GUI > > toolkits, there has been little serious development with PythonCE. > > (Little not none - and it's great to have Python available.) > > > > There is no built in support for the serial port in PythonCE (AFAIK). > > Your best bet is using ctypes (for which a PythonCE port has been done) > > and the microsoft API. > > > > Fuzzyman > > http://www.voidspace.org.uk/python/index.shtml > > > >> Regards, > >> > >> Philippe > > > > > Thanks, does that mean that I need to write an extension to the WinCE API or > is that built-into the Python package ? > (Sorry for late reply.) There is a version of ctypes *compiled* for PythonCE (from the PythonCE sourceforge page). Using ctypes you should be able to use the Microsoft Win32 API to access the serial port from *pure Python* code. You will need to use the Microsoft docs to see which calls to make. Fuzzyman http://www.voidspace.org.uk/python/index.shtml > Regards, > Philippe From jim.lewis at miclog.com Sat Jun 3 20:56:23 2006 From: jim.lewis at miclog.com (Jim Lewis) Date: 3 Jun 2006 11:56:23 -0700 Subject: Pyrex list/array Message-ID: <1149360983.373137.200740@i39g2000cwa.googlegroups.com> I'm trying to move a function into pyrex for speed. The python side needs to pass a list to the pyrex function. Do I need to convert to array or something so pyrex can generate tight code? I'm not clear how to do this. From sjmachin at lexicon.net Sun Jun 4 03:39:55 2006 From: sjmachin at lexicon.net (John Machin) Date: Sun, 04 Jun 2006 11:39:55 +1000 Subject: Pyrex list/array In-Reply-To: <1149360983.373137.200740@i39g2000cwa.googlegroups.com> References: <1149360983.373137.200740@i39g2000cwa.googlegroups.com> Message-ID: <448239EB.6010706@lexicon.net> On 4/06/2006 4:56 AM, Jim Lewis wrote: > I'm trying to move a function into pyrex for speed. You probably didn't expect the Inquisition; nobody does. But here it is, nice red uniforms and all: 1. What is your speed requirement and how far short of that are you at the moment? 2. Are you sure there is no Python or third-party module that does what you want? 3. Is your algorithm the best possible? 4. Is your Python implementation of that algorithm the best possible? Have you exposed it to the critical gaze of the speed-freaks in this newsgroup? 5. Does your architecture support psyco? If so, have you tried that and what were the results? > The python side > needs to pass a list to the pyrex function. Do I need to convert to > array or something so pyrex can generate tight code? I'm not clear how > to do this. > The question might be better asked on the Pyrex mailing list. You don't need to convert a list to a C array, and it may not even be possible, depending on what type(s) of data you have in the list. Almost any Python code is also valid Pyrex code. For a start, just compile your function with Pyrex and compare the speed. What you do next is going to depend very much on what operations you are performing on the list and the objects it contains. Watch out for Python built-ins like range, xrange, ord, chr, abs, bool, int(a_number), float(a_number), divmod, max/min (two_numeric_args). In almost all cases you get cheap wins by replacing use of these by simple C-like code -- provided of course you are absolutely sure you know what types you are dealing with. HTH, John From jim.lewis at miclog.com Sun Jun 4 11:59:00 2006 From: jim.lewis at miclog.com (Jim Lewis) Date: 4 Jun 2006 02:59:00 -0700 Subject: Pyrex list/array In-Reply-To: <448239EB.6010706@lexicon.net> References: <1149360983.373137.200740@i39g2000cwa.googlegroups.com> <448239EB.6010706@lexicon.net> Message-ID: <1149415140.458073.65310@c74g2000cwc.googlegroups.com> Thanks for your comments. > You probably didn't expect the Inquisition... Correct ;-) > 1. What is your speed requirement and how far short of that are you at the moment? ~10 times faster. > 2. Are you sure there is no Python or third-party module that does what you want? Yes. > 3. Is your algorithm the best possible? I think so although of course one can never be certain. > 4. Is your Python implementation of that algorithm the best possible? Have you exposed it to the critical gaze of the speed-freaks in this newsgroup? Thanks for the good suggestion but I want to try pyrex first. > 5. Does your architecture support psyco? If so, have you tried that and what were the results? Already using psyco. > The question might be better asked on the Pyrex mailing list. I did not find it - where is it? > Almost any Python code is also valid Pyrex code. For a start, just compile your function with Pyrex and compare the speed. It's slower. > What you do next is going to depend very much on what operations you are performing on the list and the objects it contains. Simple list of ints. Comparing sections of lists between each other. From skip at pobox.com Sun Jun 4 12:55:43 2006 From: skip at pobox.com (skip at pobox.com) Date: Sun, 4 Jun 2006 05:55:43 -0500 Subject: Pyrex list/array In-Reply-To: <1149415140.458073.65310@c74g2000cwc.googlegroups.com> References: <1149360983.373137.200740@i39g2000cwa.googlegroups.com> <448239EB.6010706@lexicon.net> <1149415140.458073.65310@c74g2000cwc.googlegroups.com> Message-ID: <17538.48175.243802.549777@montanaro.dyndns.org> >> 5. Does your architecture support psyco? If so, have you tried that >> and what were the results? Jim> Already using psyco. Is it substantially faster with psyco than without? If psyco is performing its magic on the critical section of code already, you are going to lose that when switching to Pyrex. Skip From jim.lewis at miclog.com Sun Jun 4 13:02:31 2006 From: jim.lewis at miclog.com (Jim Lewis) Date: 4 Jun 2006 04:02:31 -0700 Subject: Pyrex list/array In-Reply-To: References: <1149360983.373137.200740@i39g2000cwa.googlegroups.com> <448239EB.6010706@lexicon.net> <1149415140.458073.65310@c74g2000cwc.googlegroups.com> Message-ID: <1149418950.943306.262510@h76g2000cwa.googlegroups.com> > Is it substantially faster with psyco than without? If psyco is performing > its magic on the critical section of code already, you are going to lose > that when switching to Pyrex. Yes but from what I read Pyrex can be a lot faster than psyco under the right circumstances. From skip at pobox.com Sun Jun 4 13:22:19 2006 From: skip at pobox.com (skip at pobox.com) Date: Sun, 4 Jun 2006 06:22:19 -0500 Subject: Pyrex list/array In-Reply-To: <1149418950.943306.262510@h76g2000cwa.googlegroups.com> References: <1149360983.373137.200740@i39g2000cwa.googlegroups.com> <448239EB.6010706@lexicon.net> <1149415140.458073.65310@c74g2000cwc.googlegroups.com> <1149418950.943306.262510@h76g2000cwa.googlegroups.com> Message-ID: <17538.49771.991613.732043@montanaro.dyndns.org> >> Is it substantially faster with psyco than without? If psyco is >> performing its magic on the critical section of code already, you are >> going to lose that when switching to Pyrex. Jim> Yes but from what I read Pyrex can be a lot faster than psyco under Jim> the right circumstances. I'm sure that's true. That also means under the wrong circumstances it might not. ;-) Can you post the code that's running too slowly? Also, note that psyco learned some new tricks at the recent NeedForSpeed sprint. You might want to check out the latest version from Subversion and give it a whirl. Skip From sjmachin at lexicon.net Sun Jun 4 14:17:41 2006 From: sjmachin at lexicon.net (John Machin) Date: Sun, 04 Jun 2006 22:17:41 +1000 Subject: Pyrex list/array In-Reply-To: <1149415140.458073.65310@c74g2000cwc.googlegroups.com> References: <1149360983.373137.200740@i39g2000cwa.googlegroups.com> <448239EB.6010706@lexicon.net> <1149415140.458073.65310@c74g2000cwc.googlegroups.com> Message-ID: <4482CF65.1070506@lexicon.net> On 4/06/2006 7:59 PM, Jim Lewis wrote: > Thanks for your comments. > >> You probably didn't expect the Inquisition... > > Correct ;-) Nobody does :-) > >> The question might be better asked on the Pyrex mailing list. > > I did not find it - where is it? Evidently somewhere near the Hall of the Mountain King. A reference to it is cunningly concealed in the last place one would think of finding it: under the heading "Mailing List" on the Pyrex home page :-) Here: http://lists.copyleft.no/mailman/listinfo/pyrex ... get in quick before the pirate moves it again. > >> Almost any Python code is also valid Pyrex code. For a start, just compile your function with Pyrex and compare the speed. > > It's slower. > >> What you do next is going to depend very much on what operations you are performing on the list and the objects it contains. > > Simple list of ints. Comparing sections of lists between each other. Do you mean alist[x:x+n] == alist[y:y+n] ? If so, that's creating two new lists each of size n, and then comparing those two lists. I doubt that psyco would recognize that it didn't need to copy the two slices. The first step might be to write functions to compare without copying, e.g.: def py_slices_cmp_eq(py_list, start1, start2, size): """Return 1 if py_list[start1+size] == py_list[start2+size] else 0""" offset = start2 - start1 for i in xrange(start1, start1+size): if py_list[i] != py_list[i+offset]: return 0 return 1 See what psyco makes of that. Then turn that into a cdef function for Pyrex. If that's still not fast enough, then you might be in for some harder work: Allocate memory for a C array, unpack your list into it, write comparison functions c_slices_cmp_* that operate on your array of ints. There should be no Python stuff in there, only C constructs. You can even use memcmp() for the cmp_eq function. Which brings us back to your original question "Do I need to convert to array or something so pyrex can generate tight code?" ... 1. Some of the above may help you to determine whether you need to. 2. Without any knowledge of the size of your list or what you are doing, we can't help you much more on whether you need to. 3. AFAICT, Pyrex doesn't do much in the way of optimisation, leaving that up to the C compiler. Generating tight code would depend more on you replacing appropriately-chosen Pythonisms with C-isms. As for *how* to make your C array, something like this: cdef extern from "Python.h": void PyMem_Free(void *p) void* PyMem_Malloc(int n) except NULL # untested -- compiles OK :-) cdef int * int_array_from_list(object ilist): cdef int n, i cdef int * arrayp n = len(ilist) arrayp = PyMem_Malloc(n * sizeof(int)) for i from 0 <= i < n: arrayp[i] = ilist[i] return &arrayp[0] Hoping some of this helps, John From jim.lewis at miclog.com Sun Jun 4 15:07:01 2006 From: jim.lewis at miclog.com (Jim Lewis) Date: 4 Jun 2006 06:07:01 -0700 Subject: Pyrex list/array In-Reply-To: <4482CF65.1070506@lexicon.net> References: <1149360983.373137.200740@i39g2000cwa.googlegroups.com> <448239EB.6010706@lexicon.net> <1149415140.458073.65310@c74g2000cwc.googlegroups.com> <4482CF65.1070506@lexicon.net> Message-ID: <1149426421.864274.319290@c74g2000cwc.googlegroups.com> > cunningly concealed in the last place one would think of finding it: under the heading "Mailing List" on the Pyrex home page :-) Hmmm - maybe I should try the scroll bar occassionally ;-) > Do you mean alist[x:x+n] == alist[y:y+n] ? OK, probably you an Skip are right - let's see if I missed something at the Python level. There are essentially two differences from your snip above. I am trying to compute n and there are multiple (under 10) lists. Size of lists are typically under 100 ints. > ...See what psyco makes of that. I'm doing a similar straightforward loop approach but it's too slow. Jim From rbann11 at hotmail.com Sat Jun 3 22:25:31 2006 From: rbann11 at hotmail.com (rbann11 at hotmail.com) Date: 3 Jun 2006 13:25:31 -0700 Subject: wxpython wxgrid question Message-ID: <1149366330.999234.299880@u72g2000cwu.googlegroups.com> Hi, I am looking for example code that consists of just a frame and a grid(10x2). The grid must fill the its parent even if the frame is resized. Thanks in advance, Roger From jes at nl.demon.net Sun Jun 4 00:02:11 2006 From: jes at nl.demon.net (Jim Segrave) Date: Sat, 03 Jun 2006 22:02:11 -0000 Subject: wxpython wxgrid question References: <1149366330.999234.299880@u72g2000cwu.googlegroups.com> Message-ID: <12841n3lmt36v2a@corp.supernews.com> In article <1149366330.999234.299880 at u72g2000cwu.googlegroups.com>, wrote: >Hi, > > I am looking for example code that consists of just a frame and a >grid(10x2). The grid must fill the its parent even if the frame is >resized. This simple program makes a two element window, the lower half of which is a gridded set of labels which resize with the window. The important part is the columnconfigure() and rowconfigure() method calls on the container widget for the grid. See http://infohost.nmt.edu/tcc/help/pubs/tkinter/grid-config.html #!/usr/local/bin/python from Tkinter import * root = Tk() # create a frame (unused, but shared with gridded frame) f = Frame(height = 100) f.pack(expand = YES, fill = BOTH) # create a frame for a gridded display gf = Frame() gf.pack(expand = YES, fill = BOTH) # create a 3 x 4 array of labels, each with a different background # Make each row and column have equal weights, so they'll # grow and shrink together for row in range(3): gf.rowconfigure(row, weight = 1) for col in range(4): gf.columnconfigure(col, weight = 1) Label(gf, text = "Row: %d\nCol: %d" % (row, col), bg = "#%02x%02x%02x" % ((row * 4 + col) * 16, (row * 4 + col) * 16, (row * 4 + col) * 16), fg = "#ffffff" ).grid(row = row, column = col, sticky = NSEW) root.mainloop() -- Jim Segrave (jes at jes-2.demon.nl) From timr at probo.com Sun Jun 4 01:09:13 2006 From: timr at probo.com (Tim Roberts) Date: Sat, 03 Jun 2006 23:09:13 GMT Subject: wxpython wxgrid question References: <1149366330.999234.299880@u72g2000cwu.googlegroups.com> Message-ID: rbann11 at hotmail.com wrote: > > I am looking for example code that consists of just a frame and a >grid(10x2). The grid must fill the its parent even if the frame is >resized. Have you gone through the wxPython demo application? It contains examples of every standard control and almost every behavior you might want. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From rbann11 at hotmail.com Sun Jun 4 05:58:04 2006 From: rbann11 at hotmail.com (rbann11 at hotmail.com) Date: 3 Jun 2006 20:58:04 -0700 Subject: wxpython wxgrid question In-Reply-To: References: <1149366330.999234.299880@u72g2000cwu.googlegroups.com> Message-ID: <1149393484.553463.286220@i39g2000cwa.googlegroups.com> Tim Roberts wrote: > rbann11 at hotmail.com wrote: > > > > I am looking for example code that consists of just a frame and a > >grid(10x2). The grid must fill the its parent even if the frame is > >resized. > > Have you gone through the wxPython demo application? It contains examples > of every standard control and almost every behavior you might want. > -- > - Tim Roberts, timr at probo.com > Providenza & Boekelheide, Inc. Yes, and i have even checked out "wxpython in action". All of the examples tend to leave white space on the right of the frame. I tried basic a example with sizers and it didnt work. That why I was wondering if someone had got it to work. Roger From jmbc at nospam.fr Wed Jun 7 21:38:32 2006 From: jmbc at nospam.fr (jean-michel bain-cornu) Date: Wed, 07 Jun 2006 21:38:32 +0200 Subject: wxpython wxgrid question In-Reply-To: <1149393484.553463.286220@i39g2000cwa.googlegroups.com> References: <1149366330.999234.299880@u72g2000cwu.googlegroups.com> <1149393484.553463.286220@i39g2000cwa.googlegroups.com> Message-ID: <44872b73$0$7769$7a628cd7@news.club-internet.fr> rbann11 at hotmail.com a ?crit : > Tim Roberts wrote: >> rbann11 at hotmail.com wrote: >>> I am looking for example code that consists of just a frame and a >>> grid(10x2). The grid must fill the its parent even if the frame is >>> resized. >> Have you gone through the wxPython demo application? It contains examples >> of every standard control and almost every behavior you might want. >> -- >> - Tim Roberts, timr at probo.com >> Providenza & Boekelheide, Inc. > > Yes, and i have even checked out "wxpython in action". All of the > examples tend to leave white space on the right of the frame. I tried > basic a example with sizers and it didnt work. That why I was > wondering if someone had got it to work. > > > Roger > Hi Roger, A key point is that the Grid manages itself its available space according to the size it can have. If you just tried to create a simple grid within a simple frame, you probably got a grid filling all the frame space, and it's what you want. Why that ? If you do it (for instance with the script below), and you try to manually reduce/increase the size of the window, you should see scrollbars at the edge of the window ; these scrollbars come from the grid, because they take in account the labels row and col (wxGrid comes from wxScrolledWindow). You can see that no more space is available beyond the scrollbar, so the grid takes the whole space. And why the white space on the right ? This space is not on the right of the grid, but on the right of the last col. We could think it's like that because it's not possible to compute an appropriate col size for the grid cols, but it's not displayed exactly the same in linux and in windows. In one case it's over the last col (not enough space) and in the other case it's beyond (too much space). I think that as the program must work on all the environments, the interface must stay enough global, and sometimes the display is not perfectly done. The advantage is that if we let wx decide, we won't have to think how to set the widgets. Regards, jm #---------------------------------------------------------------------- import wx,wx.grid #---------------------------------------------------------------------- class MainWindow(wx.Frame): def __init__(self,parent,id,title): wx.Frame.__init__(self,parent,wx.ID_ANY,title) #-- self.grid= wx.grid.Grid(id=wx.ID_ANY,parent=self) self.grid.CreateGrid(numRows=10,numCols=2) self.grid.Fit() self.Fit() #-- self.Show(1) #---------------------------------------------------------------------- app = wx.PySimpleApp() frame=MainWindow(None,-1,'Grid sizer') app.MainLoop() del app #---------------------------------------------------------------------- From rbann11 at hotmail.com Fri Jun 9 23:43:59 2006 From: rbann11 at hotmail.com (rbann11 at hotmail.com) Date: 9 Jun 2006 14:43:59 -0700 Subject: wxpython wxgrid question In-Reply-To: <44872b73$0$7769$7a628cd7@news.club-internet.fr> References: <1149366330.999234.299880@u72g2000cwu.googlegroups.com> <1149393484.553463.286220@i39g2000cwa.googlegroups.com> <44872b73$0$7769$7a628cd7@news.club-internet.fr> Message-ID: <1149889439.527285.69620@c74g2000cwc.googlegroups.com> jean-michel bain-cornu wrote: > rbann11 at hotmail.com a ?crit : > > Tim Roberts wrote: > >> rbann11 at hotmail.com wrote: > >>> I am looking for example code that consists of just a frame and a > >>> grid(10x2). The grid must fill the its parent even if the frame is > >>> resized. > >> Have you gone through the wxPython demo application? It contains examples > >> of every standard control and almost every behavior you might want. > >> -- > >> - Tim Roberts, timr at probo.com > >> Providenza & Boekelheide, Inc. > > > > Yes, and i have even checked out "wxpython in action". All of the > > examples tend to leave white space on the right of the frame. I tried > > basic a example with sizers and it didnt work. That why I was > > wondering if someone had got it to work. > > > > > > Roger > > > Hi Roger, > A key point is that the Grid manages itself its available space > according to the size it can have. > If you just tried to create a simple grid within a simple frame, you > probably got a grid filling all the frame space, and it's what you want. > Why that ? > If you do it (for instance with the script below), and you try to > manually reduce/increase the size of the window, you should see > scrollbars at the edge of the window ; these scrollbars come from the > grid, because they take in account the labels row and col (wxGrid comes > from wxScrolledWindow). You can see that no more space is available > beyond the scrollbar, so the grid takes the whole space. > And why the white space on the right ? This space is not on the right of > the grid, but on the right of the last col. We could think it's like > that because it's not possible to compute an appropriate col size for > the grid cols, but it's not displayed exactly the same in linux and in > windows. In one case it's over the last col (not enough space) and in > the other case it's beyond (too much space). I think that as the program > must work on all the environments, the interface must stay enough > global, and sometimes the display is not perfectly done. > The advantage is that if we let wx decide, we won't have to think how to > set the widgets. > Regards, > jm > > #---------------------------------------------------------------------- > import wx,wx.grid > #---------------------------------------------------------------------- > class MainWindow(wx.Frame): > def __init__(self,parent,id,title): > wx.Frame.__init__(self,parent,wx.ID_ANY,title) > #-- > self.grid= wx.grid.Grid(id=wx.ID_ANY,parent=self) > self.grid.CreateGrid(numRows=10,numCols=2) > self.grid.Fit() > self.Fit() > #-- > self.Show(1) > #---------------------------------------------------------------------- > app = wx.PySimpleApp() > frame=MainWindow(None,-1,'Grid sizer') > app.MainLoop() > del app > #---------------------------------------------------------------------- Thanks Tim, I knew it was something like that, but I had to ask the question. I was hoping that there was a way around the problem. Roger From rbann11 at hotmail.com Fri Jun 9 23:43:59 2006 From: rbann11 at hotmail.com (rbann11 at hotmail.com) Date: 9 Jun 2006 14:43:59 -0700 Subject: wxpython wxgrid question In-Reply-To: <44872b73$0$7769$7a628cd7@news.club-internet.fr> References: <1149366330.999234.299880@u72g2000cwu.googlegroups.com> <1149393484.553463.286220@i39g2000cwa.googlegroups.com> <44872b73$0$7769$7a628cd7@news.club-internet.fr> Message-ID: <1149889439.662650.154260@f6g2000cwb.googlegroups.com> jean-michel bain-cornu wrote: > rbann11 at hotmail.com a ?crit : > > Tim Roberts wrote: > >> rbann11 at hotmail.com wrote: > >>> I am looking for example code that consists of just a frame and a > >>> grid(10x2). The grid must fill the its parent even if the frame is > >>> resized. > >> Have you gone through the wxPython demo application? It contains examples > >> of every standard control and almost every behavior you might want. > >> -- > >> - Tim Roberts, timr at probo.com > >> Providenza & Boekelheide, Inc. > > > > Yes, and i have even checked out "wxpython in action". All of the > > examples tend to leave white space on the right of the frame. I tried > > basic a example with sizers and it didnt work. That why I was > > wondering if someone had got it to work. > > > > > > Roger > > > Hi Roger, > A key point is that the Grid manages itself its available space > according to the size it can have. > If you just tried to create a simple grid within a simple frame, you > probably got a grid filling all the frame space, and it's what you want. > Why that ? > If you do it (for instance with the script below), and you try to > manually reduce/increase the size of the window, you should see > scrollbars at the edge of the window ; these scrollbars come from the > grid, because they take in account the labels row and col (wxGrid comes > from wxScrolledWindow). You can see that no more space is available > beyond the scrollbar, so the grid takes the whole space. > And why the white space on the right ? This space is not on the right of > the grid, but on the right of the last col. We could think it's like > that because it's not possible to compute an appropriate col size for > the grid cols, but it's not displayed exactly the same in linux and in > windows. In one case it's over the last col (not enough space) and in > the other case it's beyond (too much space). I think that as the program > must work on all the environments, the interface must stay enough > global, and sometimes the display is not perfectly done. > The advantage is that if we let wx decide, we won't have to think how to > set the widgets. > Regards, > jm > > #---------------------------------------------------------------------- > import wx,wx.grid > #---------------------------------------------------------------------- > class MainWindow(wx.Frame): > def __init__(self,parent,id,title): > wx.Frame.__init__(self,parent,wx.ID_ANY,title) > #-- > self.grid= wx.grid.Grid(id=wx.ID_ANY,parent=self) > self.grid.CreateGrid(numRows=10,numCols=2) > self.grid.Fit() > self.Fit() > #-- > self.Show(1) > #---------------------------------------------------------------------- > app = wx.PySimpleApp() > frame=MainWindow(None,-1,'Grid sizer') > app.MainLoop() > del app > #---------------------------------------------------------------------- Thanks Tim, I knew it was something like that, but I had to ask the question. I was hoping that there was a way around the problem. Roger From cito at online.de Sat Jun 3 23:23:32 2006 From: cito at online.de (Christoph Zwerschke) Date: Sat, 03 Jun 2006 23:23:32 +0200 Subject: Python less error-prone than Java Message-ID: You will often hear that for reasons of fault minimization, you should use a programming language with strict typing: http://turing.une.edu.au/~comp284/Lectures/Lecture_18/lecture/node1.html I just came across a funny example in which the opposite is the case. The following is a binary search algorithm in Java. It searches a value in an ordered array a of ints: public static int binarySearch(int[] a, int key) { int low = 0; int high = a.length - 1; while (low <= high) { int mid = (low + high) / 2; int midVal = a[mid]; if (midVal < key) low = mid + 1; else if (midVal > key) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found. } Now the same thing, directly converted to Python: def binarySearch(a, key): low = 0 high = len(a) - 1 while low <= high: mid = (low + high) / 2 midVal = a[mid] if midVal < key: low = mid + 1 elif midVal > key: high = mid - 1; else: return mid # key found return -(low + 1) # key not found. What's better about the Python version? First, it will operate on *any* sorted array, no matter which type the values have. But second, there is a hidden error in the Java version that the Python version does not have. See the following web page if you dont find it ;-) http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html -- Christoph From claird at lairds.us Sun Jun 4 01:48:20 2006 From: claird at lairds.us (Cameron Laird) Date: Sat, 3 Jun 2006 23:48:20 +0000 Subject: Python less error-prone than Java References: Message-ID: <4nj9l3-hgn.ln1@lairds.us> In article , Christoph Zwerschke wrote: >You will often hear that for reasons of fault minimization, you should >use a programming language with strict typing: >http://turing.une.edu.au/~comp284/Lectures/Lecture_18/lecture/node1.html > >I just came across a funny example in which the opposite is the case. . . . >What's better about the Python version? First, it will operate on *any* >sorted array, no matter which type the values have. > >But second, there is a hidden error in the Java version that the Python >version does not have. > >See the following web page if you dont find it ;-) >http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html . . . This is all worth saying, that is, I agree with the conclusions. The premises are arguable, though. For me, this example illustrates the difficulty faced by people who hear, "strict typing", and think of Java. At another level, Python's superiority here is epiphenomenal. Python probably has a better model for arithmetic than Java, but BDFL knows that Python is not without its own flaws, particulary in arithmetic. So, here's my summary: Python's a nice language--a very nice one. It's safer to use than Java in many ways. Python's typing is STRICTER than Java's, but it's also dynamic, so people get to argue for decades about which is a better model. Anyone who thinks typing is a first-order determinant of code quality is making a big mistake though, anyway. From cito at online.de Sun Jun 4 03:49:23 2006 From: cito at online.de (Christoph Zwerschke) Date: Sun, 04 Jun 2006 03:49:23 +0200 Subject: Python less error-prone than Java In-Reply-To: <4nj9l3-hgn.ln1@lairds.us> References: <4nj9l3-hgn.ln1@lairds.us> Message-ID: Cameron Laird wrote: > So, here's my summary: Python's a nice language--a very nice one. > It's safer to use than Java in many ways. Python's typing is > STRICTER than Java's, but it's also dynamic, so people get to argue > for decades about which is a better model. Anyone who thinks typing > is a first-order determinant of code quality is making a big mistake > though, anyway. Yes, sorry. It has nothing to do with strict, but with static typing. And I should not have chosen such a general subject line (I just meant to be funny, but sounded more like a troll). I had just noticed that the direct translation of that Java program to Python would not have that subtle bug and found that this was worth mentioning. -- Christoph From percivall at gmail.com Sun Jun 4 01:52:19 2006 From: percivall at gmail.com (Simon Percivall) Date: 3 Jun 2006 16:52:19 -0700 Subject: Python less error-prone than Java References: Message-ID: <1149378739.429512.26310@f6g2000cwb.googlegroups.com> Actually, you're wrong on all levels. First: It's perfectly simple in Java to create a binary sort that sorts all arrays that contain objects; so wrong there. Secondly: The bug has nothing to do with static typing (I'm guessing that's what you meant. Both Python and Java are strongly typed). The problem is that ints are bounded in Java. They could easily have been ints and then automatically coerced to (equivalent to) longs when they got bigger; that they aren't is more a design fault than anything to do with static typing. The equivalent in Python would have been if an overflow exception was raised when the int got too big. It might have been that way, typing or no typing. Christoph Zwerschke wrote: > You will often hear that for reasons of fault minimization, you should > use a programming language with strict typing: > http://turing.une.edu.au/~comp284/Lectures/Lecture_18/lecture/node1.html > > I just came across a funny example in which the opposite is the case. > > The following is a binary search algorithm in Java. It searches a value > in an ordered array a of ints: > > public static int binarySearch(int[] a, int key) { > int low = 0; > int high = a.length - 1; > while (low <= high) { > int mid = (low + high) / 2; > int midVal = a[mid]; > if (midVal < key) > low = mid + 1; > else if (midVal > key) > high = mid - 1; > else > return mid; // key found > } > return -(low + 1); // key not found. > } > > Now the same thing, directly converted to Python: > > def binarySearch(a, key): > low = 0 > high = len(a) - 1 > while low <= high: > mid = (low + high) / 2 > midVal = a[mid] > if midVal < key: > low = mid + 1 > elif midVal > key: > high = mid - 1; > else: > return mid # key found > return -(low + 1) # key not found. > > What's better about the Python version? First, it will operate on *any* > sorted array, no matter which type the values have. > > But second, there is a hidden error in the Java version that the Python > version does not have. > > See the following web page if you dont find it ;-) > http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html > > -- Christoph From aleax at mac.com Sun Jun 4 02:07:48 2006 From: aleax at mac.com (Alex Martelli) Date: Sat, 3 Jun 2006 17:07:48 -0700 Subject: Python less error-prone than Java References: <1149378739.429512.26310@f6g2000cwb.googlegroups.com> Message-ID: <1hgd8qo.8h0orqhpo6bcN%aleax@mac.com> Simon Percivall wrote: ... > with static typing. The equivalent in Python would have been if an > overflow exception was raised when the int got too big. It might have > been that way, typing or no typing. Indeed, it _used_ to be that way -- STILL says...: exception OverflowError Raised when the result of an arithmetic operation is too large to be represented. This cannot occur for long integers (which would rather raise MemoryError than give up). Because of the lack of standardization of floating point exception handling in C, most floating point operations also aren't checked. For plain integers, all operations that can overflow are checked except left shift, where typical applications prefer to drop bits than raise an exception. Actually, the docs are obsolete on this point, and an int becomes a long when that's necessary: >>> sys.maxint+1 2147483648L but, this operation _would_ have raised OverflowError in old-enough versions of Python (not sure exactly when the switch happened...). Alex From cito at online.de Sun Jun 4 03:36:50 2006 From: cito at online.de (Christoph Zwerschke) Date: Sun, 04 Jun 2006 03:36:50 +0200 Subject: Python less error-prone than Java In-Reply-To: <1149378739.429512.26310@f6g2000cwb.googlegroups.com> References: <1149378739.429512.26310@f6g2000cwb.googlegroups.com> Message-ID: Simon Percivall wrote: > First: It's perfectly simple in Java to create a binary sort that > sorts all arrays that contain objects; so wrong there. My point was that the *same* Java source example, directly converted to Python would *automatically* accept all kinds of arrays. No need to make any extra efforts. By the way, how would you do it in Java? With function overloading? I would not call that perfectly simple. > Secondly: The bug has nothing to do with static typing (I'm guessing > that's what you meant. Both Python and Java are strongly typed). The > problem is that ints are bounded in Java. They could easily have been > ints and then automatically coerced to (equivalent to) longs when they > got bigger; that they aren't is more a design fault than anything to > do with static typing. The equivalent in Python would have been if an > overflow exception was raised when the int got too big. It might have > been that way, typing or no typing. Yes, sorry, I meant static typing, not strict typing. But I still do think that the bug has to do with static typing. You're right, the direct cause is that ints are bounded in Java, and not bounded in Python, and that it could well be the other way round. However, doing it the other way round would not be so clever and appropriate for the respective language due to the difference in static typing. Java could coerce the result to long, but then it would still crash when the result is stored back to the statically typed variable. So that would not be very clever. And Python could produce an overflow error (and did in the past), but taking advantage of the possibilities of dynamic typing and automatically producing longs is a cleverer solution for Python, and that's why it was proposed and accepted in PEP237. So the difference in static typing is actually the deeper reason why ints were made to behave differently in the two languages. -- Christoph From amorgan at xenon.Stanford.EDU Sun Jun 4 04:52:13 2006 From: amorgan at xenon.Stanford.EDU (Alan Morgan) Date: Sat, 3 Jun 2006 19:52:13 -0700 (PDT) Subject: Python less error-prone than Java References: <1149378739.429512.26310@f6g2000cwb.googlegroups.com> Message-ID: In article , Christoph Zwerschke wrote: >Simon Percivall wrote: > > First: It's perfectly simple in Java to create a binary sort that > > sorts all arrays that contain objects; so wrong there. > >My point was that the *same* Java source example, directly converted to >Python would *automatically* accept all kinds of arrays. And the same code converted to SML would automatically work on all kinds of arrays and SML is statically typed. It's a language issue, not a typing issue. >No need to make any extra efforts. >By the way, how would you do it in Java? With >function overloading? I would not call that perfectly simple. Since Java doesn't allow function overloading that clearly can't be the way. J2SE 5.0 allows generic classes and functions that operate on generic containers. There are some gotchas, but it's not drastically more complex than the original int-only java code. Alan -- Defendit numerus From nyamatongwe+thunder at gmail.com Sun Jun 4 07:08:15 2006 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Sun, 04 Jun 2006 05:08:15 GMT Subject: Python less error-prone than Java In-Reply-To: References: <1149378739.429512.26310@f6g2000cwb.googlegroups.com> Message-ID: <3Vtgg.2967$ap3.12@news-server.bigpond.net.au> Alan Morgan wrote: > Since Java doesn't allow function overloading that clearly can't be > the way. J2SE 5.0 allows generic classes and functions that operate > on generic containers. There are some gotchas, but it's not drastically > more complex than the original int-only java code. Doesn't Java restrict generics to only operate on reference types so you can't produce a generic binary search that operates on arrays where the item type may be int? Neil From amorgan at xenon.Stanford.EDU Sun Jun 4 07:12:52 2006 From: amorgan at xenon.Stanford.EDU (Alan Morgan) Date: Sat, 3 Jun 2006 22:12:52 -0700 (PDT) Subject: Python less error-prone than Java References: <3Vtgg.2967$ap3.12@news-server.bigpond.net.au> Message-ID: In article <3Vtgg.2967$ap3.12 at news-server.bigpond.net.au>, Neil Hodgson wrote: >Alan Morgan wrote: > >> Since Java doesn't allow function overloading that clearly can't be >> the way. J2SE 5.0 allows generic classes and functions that operate >> on generic containers. There are some gotchas, but it's not drastically >> more complex than the original int-only java code. > > Doesn't Java restrict generics to only operate on reference types so >you can't produce a generic binary search that operates on arrays where >the item type may be int? Yup, you have to wrap int (and double and float and...). Blame type erasure. Alan -- Defendit numerus From cito at online.de Sun Jun 4 11:12:09 2006 From: cito at online.de (Christoph Zwerschke) Date: Sun, 04 Jun 2006 11:12:09 +0200 Subject: Python less error-prone than Java In-Reply-To: References: <1149378739.429512.26310@f6g2000cwb.googlegroups.com> Message-ID: >> Simon Percivall wrote: >>> First: It's perfectly simple in Java to create a binary sort that >>> sorts all arrays that contain objects; so wrong there. >> My point was that the *same* Java source example, directly converted to >> Python would *automatically* accept all kinds of arrays. > > And the same code converted to SML would automatically work on all > kinds of arrays and SML is statically typed. It's a language issue, > not a typing issue. Ok, here the point was that Java has *explicit* static typing. SML is not a procedural language and uses *implicit* static typing. Therefore it shares some of the benefits of dynamically typed languages such as Python. However, an SML version of the program would probably still have the same bug as the Java version, right? >> No need to make any extra efforts. >> By the way, how would you do it in Java? With >> function overloading? I would not call that perfectly simple. > > Since Java doesn't allow function overloading that clearly can't be > the way. J2SE 5.0 allows generic classes and functions that operate > on generic containers. There are some gotchas, but it's not drastically > more complex than the original int-only java code. Java doesn't allow function overloading? That would be new to me. Or did you just want to nitpick that it should be more properly called "method overloading" in Java? And as you already said, there are some gotchas and you would have to wrap int and long etc. I still would not call that perfectly simple, as it is in Python. -- Christoph From amorgan at xenon.Stanford.EDU Sun Jun 4 23:03:09 2006 From: amorgan at xenon.Stanford.EDU (Alan Morgan) Date: Sun, 4 Jun 2006 14:03:09 -0700 (PDT) Subject: Python less error-prone than Java References: Message-ID: In article , Christoph Zwerschke wrote: >>> Simon Percivall wrote: >>>> First: It's perfectly simple in Java to create a binary sort that >>>> sorts all arrays that contain objects; so wrong there. >>> My point was that the *same* Java source example, directly converted to >>> Python would *automatically* accept all kinds of arrays. >> >> And the same code converted to SML would automatically work on all >> kinds of arrays and SML is statically typed. It's a language issue, >> not a typing issue. > >Ok, here the point was that Java has *explicit* static typing. SML is >not a procedural language and uses *implicit* static typing. Therefore >it shares some of the benefits of dynamically typed languages such as >Python. However, an SML version of the program would probably still have >the same bug as the Java version, right? > >>> No need to make any extra efforts. >>> By the way, how would you do it in Java? With >>> function overloading? I would not call that perfectly simple. >> >> Since Java doesn't allow function overloading that clearly can't be >> the way. J2SE 5.0 allows generic classes and functions that operate >> on generic containers. There are some gotchas, but it's not drastically >> more complex than the original int-only java code. > >Java doesn't allow function overloading? Brain fart. You said "function" and I read "operator". Alan -- Defendit numerus From iny+news at iki.fi Sun Jun 4 07:37:38 2006 From: iny+news at iki.fi (Ilpo =?iso-8859-1?Q?Nyyss=F6nen?=) Date: Sun, 04 Jun 2006 08:37:38 +0300 Subject: Python less error-prone than Java References: Message-ID: Christoph Zwerschke writes: > What's better about the Python version? First, it will operate on > *any* sorted array, no matter which type the values have. > > But second, there is a hidden error in the Java version that the > Python version does not have. While I can see your point, I'd say you are totally in the wrong level here. With Java generics you can sort a list and still keeping the type of the contents defined. This is makes the code less error-prone. But why would you implement binary search as the standard library already has it for both arrays and lists? This is one big thing that makes code less error-prone: using existing well made libraries. You can find binary search from python standard library too (but actually the API in Java is a bit better, see the return values). Well, you can say that the binary search is a good example and in real code you would use the stuff from the libraries. I'd say it is not good example: How often will you write such algorithms? Very rarely. Integer overflows generally are not those errors you run into in programs. The errors happening most often are from my point of view: 1. null pointer errors 2. wrong type (class cast in Java, some weird missing attribute in python) 3. array/list index out of bounds First and third ones are the same in about every language. The second one is one where the typing can make a difference. If in the code level you know the type all the way, there is much less changes of it being wrong. (The sad thing in the Java generics is that it is a compile time only thing and that causes some really weird stuff, but that is too off topic to here.) In python passing sequences for a function and also from a function is very easy. You can very easily pass a sequence as argument list. You can also very easily return a sequence from the function and even split it to variables directly. This is very powerful tool, but it has a problem too: How can you change what you return without breaking the callers? There are many cases where passing an object instead of a sequence makes the code much easier to develop further. What's the point? The point is that neither with Java or Python you want to be doing things in the low level. You really want to be doing stuff with objects and using existing libraries as much as possible. And in that level Java might be less error-prone as it does restrict the ways you can shoot yourself more. -- Ilpo Nyyss?nen # biny # /* :-) */ From kkylheku at gmail.com Sun Jun 4 10:13:44 2006 From: kkylheku at gmail.com (Kaz Kylheku) Date: 4 Jun 2006 01:13:44 -0700 Subject: Python less error-prone than Java In-Reply-To: References: Message-ID: <1149408824.174844.178010@u72g2000cwu.googlegroups.com> Ilpo Nyyss?nen wrote: > This is one big thing that makes code > less error-prone: using existing well made libraries. > You can find binary search from python standard library too (but actually the API > in Java is a bit better, see the return values). > Well, you can say that the binary search is a good example and in real > code you would use the stuff from the libraries. The trouble with your point is that Christoph's original posting refers to an article, which, in turn, at the bottom, refers to a bug database which shows that the very same defect had been found in Sun's Java library! Buggy library code is what prompted that article. > I'd say it is not > good example: How often will you write such algorithms? Very rarely. > > Integer overflows generally are not those errors you run into in > programs. Except when you feed those programs inputs which are converted to integers which are then fed as domain values into some operation that doesn't fit into the range type. Other than that, you are okay! Like when would that happen, right? > The errors happening most often are from my point of view: > > 1. null pointer errors > 2. wrong type (class cast in Java, some weird missing attribute in python) > 3. array/list index out of bounds > > First and third ones are the same in about every language. ... other than C and C++, where their equivalents just crash or stomp over memory, but never mind; who uses those? ;) > The second > one is one where the typing can make a difference. Actually, the first one is also where typing can make a difference. Instead of this stupid idea of pointers or references having a null value, you can make a null value which has its own type, and banish null pointers. So null pointer errors are transformed into type errors: the special value NIL was fed into an operation where some other type was expected. And by means of type polymorphism, an operation can be extended to handle the case of NIL. From fredrik at pythonware.com Sun Jun 4 11:22:42 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 04 Jun 2006 11:22:42 +0200 Subject: Python less error-prone than Java In-Reply-To: <1149408824.174844.178010@u72g2000cwu.googlegroups.com> References: <1149408824.174844.178010@u72g2000cwu.googlegroups.com> Message-ID: Kaz Kylheku wrote: > The trouble with your point is that Christoph's original posting refers > to an article, which, in turn, at the bottom, refers to a bug database > which shows that the very same defect had been found in Sun's Java > library! and as he points out at the top, it was the article author himself who wrote that library code: /.../ let me tell you how I discovered the bug: The version of binary search that I wrote for the JDK contained the same bug. It was reported to Sun recently when it broke someone's program, after lying in wait for nine years or so. From iny+news at iki.fi Mon Jun 5 06:49:52 2006 From: iny+news at iki.fi (Ilpo =?iso-8859-1?Q?Nyyss=F6nen?=) Date: Mon, 05 Jun 2006 07:49:52 +0300 Subject: Python less error-prone than Java References: <1149408824.174844.178010@u72g2000cwu.googlegroups.com> Message-ID: "Kaz Kylheku" writes: > Buggy library code is what prompted that article. Yes, but it is an error type that happens very rarely still. And so it seems that very few programs even notice that bug in that library. > Except when you feed those programs inputs which are converted to > integers which are then fed as domain values into some operation that > doesn't fit into the range type. If the input value range is limited, you want to get an error, if out of range value is given. If you want to handle unlimited values, you really need to take a look that you can do it. Think for example storing such value to a database. >> 1. null pointer errors >> 2. wrong type (class cast in Java, some weird missing attribute in python) >> 3. array/list index out of bounds >> >> First and third ones are the same in about every language. > > ... other than C and C++, where their equivalents just crash or stomp > over memory, but never mind; who uses those? ;) It is not different. Your crash can tell you that it was a null pointer. Your crash can tell you that you stomped over memory. You just get the information about the error in different way. > Instead of this stupid idea of pointers or references having a null > value, you can make a null value which has its own type, and banish > null pointers. Yes and I actually think that as bad thing. It is nice to be able to tell the difference between null pointer and wrong type. Of course if the error message tells you that you had null there, it is not a problem, but what if you somehow lose the error message and get only the exception class name? (Yes, you should always keep the message too, but it does happen.) -- Ilpo Nyyss?nen # biny # /* :-) */ From martin at v.loewis.de Mon Jun 5 10:11:50 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 05 Jun 2006 10:11:50 +0200 Subject: Python less error-prone than Java In-Reply-To: References: <1149408824.174844.178010@u72g2000cwu.googlegroups.com> Message-ID: <4483E746.8010801@v.loewis.de> Ilpo Nyyss?nen wrote: >> Buggy library code is what prompted that article. > > Yes, but it is an error type that happens very rarely still. And so it > seems that very few programs even notice that bug in that library. That's certainly the case. The bug went unnoticed in the Java library for nearly a decade, despite Java being used fairly widely. The OP's point is not that the bug might be "minor": the point is that an algorithm who was studied hundreds of times in computer science courses, repeated many times in the literature, and proven "correct" many times, still is wrong, and that the error primarily arises from using a type declaration. > If the input value range is limited, you want to get an error, if out > of range value is given. If you want to handle unlimited values, you > really need to take a look that you can do it. Think for example > storing such value to a database. So the real design flaw in Java is that int addition doesn't raise exceptions on overflow? That wouldn't have helped - the algorithm still would have been wrong, and people still would have noticed only when it happens (just as they get an exception now: array index out of bounds) Regards, Martin From cito at online.de Mon Jun 5 12:07:55 2006 From: cito at online.de (Christoph Zwerschke) Date: Mon, 05 Jun 2006 12:07:55 +0200 Subject: Python less error-prone than Java In-Reply-To: References: <1149408824.174844.178010@u72g2000cwu.googlegroups.com> Message-ID: Ilpo Nyyss?nen wrote: > It is not different. Your crash can tell you that it was a null > pointer. Your crash can tell you that you stomped over memory. You > just get the information about the error in different way. Not all stomping over memory must result in a crash. You might just get wrong results, and you don't notice it. Also, if you get such a crash it's much harder to find out the reason. It may show off only later in a different part of the program. -- Chris From kkylheku at gmail.com Sun Jun 4 09:26:38 2006 From: kkylheku at gmail.com (Kaz Kylheku) Date: 4 Jun 2006 00:26:38 -0700 Subject: Python less error-prone than Java In-Reply-To: References: Message-ID: <1149405998.784652.68510@y43g2000cwc.googlegroups.com> Christoph Zwerschke wrote: > You will often hear that for reasons of fault minimization, you should > use a programming language with strict typing: > http://turing.une.edu.au/~comp284/Lectures/Lecture_18/lecture/node1.html Quoting from that web page: "A programming language with strict typing and run-time checking should be used." This doesn't prescribe latent or manifest typing, only that there be type checking. There is no question that for reliability, it is necessary to have type checking, whether at run time or earlier. You can have statically typed languages with inadequate type safety, and you can have dynamically typed languages with inadequate type safety. > Now the same thing, directly converted to Python: > > def binarySearch(a, key): > low = 0 > high = len(a) - 1 > while low <= high: > mid = (low + high) / 2 > midVal = a[mid] > if midVal < key: > low = mid + 1 > elif midVal > key: > high = mid - 1; > else: > return mid # key found > return -(low + 1) # key not found. > > What's better about the Python version? First, it will operate on *any* > sorted array, no matter which type the values have. Uh huh! With hard-coded < and = operators, how stupid. What if you want to use it on strings? Would that be a case-insensitive lexicographic comparison, or case-insensitive? How do you specify what kind of less-than and equal you want to do? -1 to indicate not found? Why copy Java braindamage induced by an antiquated form of static typing? The Java version has to do that because the return value is necessarily declared to be of type integer. ;; Common Lisp ;; Binary search any sorted sequence SEQ for ITEM, returning ;; the position (starting from zero) if the item is found, ;; otherwise returns NIL. ;; ;; :REF specifies positional accessing function, default is ELT ;; :LEN specifies function for retrieving sequence length ;; :LESS specifies function for less-than item comparison ;; :SAME specifies function for equality comparison (defun binary-search (seq item &key (ref #'elt) (len #'length) (less #'<) (same #'=)) (loop with low = 0 and high = (funcall len seq) while (<= low high) do (let* ((mid (truncate (+ low high) 2)) (mid-val (funcall ref seq mid))) (cond ((funcall less mid-val item) (setf low (1+ mid))) ((funcall same mid-val item) (return mid)) (t (setf high (1- mid))))))) Common Lisp integers are "mathematical", so the overflow problem described in your referenced article doesn't exist here. From __peter__ at web.de Sun Jun 4 10:00:43 2006 From: __peter__ at web.de (Peter Otten) Date: Sun, 04 Jun 2006 10:00:43 +0200 Subject: Python less error-prone than Java References: <1149405998.784652.68510@y43g2000cwc.googlegroups.com> Message-ID: Kaz Kylheku wrote: > Would that be a case-insensitive lexicographic comparison, or > case-insensitive? How do you specify what kind of less-than and equal > you want to do? class Key(object): def __init__(self, value, key): self.keyval = key(value) self.key = key def __lt__(self, other): return self.keyval < self.key(other) def __gt__(self, other): return self.keyval > self.key(other) items = ["Alpha", "Beta", "Delta", "Gamma"] print binarySearch(items, Key("DELTA", str.lower)) # 2 You /can/ teach an old duck new tricks :-) Peter From cito at online.de Sun Jun 4 11:43:06 2006 From: cito at online.de (Christoph Zwerschke) Date: Sun, 04 Jun 2006 11:43:06 +0200 Subject: Python less error-prone than Java In-Reply-To: <1149405998.784652.68510@y43g2000cwc.googlegroups.com> References: <1149405998.784652.68510@y43g2000cwc.googlegroups.com> Message-ID: Kaz Kylheku wrote: > You can have statically typed languages with inadequate type safety, > and you can have dynamically typed languages with inadequate type > safety. But the point in this example was that the Java program ironically had the bug *because* Java handles ints in a type-safe way, while Python does not. >> What's better about the Python version? First, it will operate on >> *any* sorted array, no matter which type the values have. > > Uh huh! With hard-coded < and = operators, how stupid. What if you > want to use it on strings? > Would that be a case-insensitive lexicographic comparison, or > case-insensitive? How do you specify what kind of less-than and equal > you want to do? Where's the problem? The function uses the standard ordering of the values you feed to it, i.e. case-insensitive lexicographical order if you feed a lis of ordinary tuples of strings. You can also feed objects with a different ordering, like case-insensitive. Anyway, that was completely not the point. The point was that you could take that Java program, convert it directly to Python, and have automatically eliminated a bug. I did not claim that the resulting Python program was automatically a real good and Pythonic one. > -1 to indicate not found? Why copy Java braindamage induced by an > antiquated form of static typing? The Java version has to do that So you would call Python's str.find() method braindamaged as well? But as I said, that was not the point here anyway. -- Christoph From n.estner at gmx.de Sun Jun 4 14:41:23 2006 From: n.estner at gmx.de (nikie) Date: 4 Jun 2006 05:41:23 -0700 Subject: Python less error-prone than Java References: Message-ID: <1149424883.529756.13700@j55g2000cwa.googlegroups.com> Let's look at two different examples: Consider the following C# code: static decimal test() { decimal x = 10001; x /= 100; x -= 100; return x; } It returns "0.01", as you would expect it. Now, consider the python equivalent: def test(): x = 10001 x /= 100 x -= 100 return x It returns "0". Clearly an error! Even if you used "from __future__ import division", it would actually return "0.010000000000005116", which, depending on the context, may still be an intolerable error. Morale: the problem isn't whether the the types are chosen at compile-time or at runtime, it's simply _what_ type is chosen, and whether it's appropriate or not. I can even think of an example where C's (and Java's) bounded ints are the right choice, while Python's arbitraty-precision math isn't: Assume you get two 32-bit integers containing two time values (or values from an incremental encoder, or counter values). How do you find out how many timer ticks (or increments, or counts) have occured between those two values, and which one was earlier? In C, you can just write: long Distance(long t1, long t0) { return t1-t0; } And all the wraparound cases will be handled correctly (assuming there have been less than 2^31 timer ticks between these two time values). "Distance" will return a positive value if t1 was measured after t0, a negative value otherwise, even if there's been a wraparound in between. Try the same in Python and tell me which version is simpler! From cito at online.de Sun Jun 4 20:25:31 2006 From: cito at online.de (Christoph Zwerschke) Date: Sun, 04 Jun 2006 20:25:31 +0200 Subject: Python less error-prone than Java In-Reply-To: <1149424883.529756.13700@j55g2000cwa.googlegroups.com> References: <1149424883.529756.13700@j55g2000cwa.googlegroups.com> Message-ID: nikie wrote: > Let's look at two different examples: Consider the following C# code: > > static decimal test() { > decimal x = 10001; > x /= 100; > x -= 100; > return x; > > It returns "0.01", as you would expect it. Yes, I would expect that because I have defined x as decimal, not int. > Now, consider the python equivalent: > > def test(): > x = 10001 > x /= 100 > x -= 100 > return x No, that's not the Python equivalent. The equivalent of the line decimal x = 10001 in Python would be x = 10001.0 or even: from decimal import Decimal x = Decimal(10001) Setting x = 10001 would be equivalent to the C# code int x = 10001 > It returns "0". Clearly an error! That's not clearly an error. If you set int x = 10001 in C#, then you also get a "0". By setting x to be an integer, you are implicitely telling Python that you are not interested in fractions, and Python does what you want. Granted, this is arguable and will be changed in the __future__, but I would not call that an error. By the way, the equivalent Python code to your C# program gives on my machine the very same result: >>> x = 10001.0; x /= 100; x -= 100; print x 0.01 > Even if you used "from __future__ import division", it would actually > return "0.010000000000005116", which, depending on the context, may > still be an intolerable error. With from __future__ import division, I also get 0.01 printed. Anyway, if there are small discrepancies then these have nothing to do with Python but rather with the underlying floating-point hardware and C library, the way how you print the value and the fact that 0.01 can principally not be stored exactly as a float (nor as a C# decimal), only as a Python Decimal. > I can even think of an example where C's (and Java's) bounded ints are > the right choice, while Python's arbitraty-precision math isn't: > Assume you get two 32-bit integers containing two time values (or > values from an incremental encoder, or counter values). How do you > find out how many timer ticks (or increments, or counts) have occured > between those two values, and which one was earlier? In C, you can > just write: > > long Distance(long t1, long t0) { return t1-t0; } > > And all the wraparound cases will be handled correctly (assuming there > have been less than 2^31 timer ticks between these two time values). > "Distance" will return a positive value if t1 was measured after t0, a > negative value otherwise, even if there's been a wraparound in > between. Try the same in Python and tell me which version is simpler! First of all, the whole problem only arises because you are using a statically typed counter ;-) And it only is easy in C when your counter has 32 bits. But what about a 24 bit counter? Anyway, in Python, you would first define: def wrap(x, at=1<<31): if x < -at: x += at*2 elif x >= at: x -= at*2 return x Then, the Python program would be as simple: Distance = lambda t1,t0: wrap(t1-t0) -- Christoph From n.estner at gmx.de Sun Jun 4 22:30:00 2006 From: n.estner at gmx.de (nikie) Date: 4 Jun 2006 13:30:00 -0700 Subject: Python less error-prone than Java References: <1149424883.529756.13700@j55g2000cwa.googlegroups.com> Message-ID: <1149453000.162259.105090@y43g2000cwc.googlegroups.com> Christoph Zwerschke wrote: > nikie wrote: > > Let's look at two different examples: Consider the following C# code: > > > > static decimal test() { > > decimal x = 10001; > > x /= 100; > > x -= 100; > > return x; > > > > It returns "0.01", as you would expect it. > > Yes, I would expect that because I have defined x as decimal, not int. > > > Now, consider the python equivalent: > > > > def test(): > > x = 10001 > > x /= 100 > > x -= 100 > > return x > > No, that's not the Python equivalent. The equivalent of the line > > decimal x = 10001 > > in Python would be > > x = 10001.0 > > or even: > > from decimal import Decimal > x = Decimal(10001) Hm, then I probably didn't get your original point: I thought your argument was that a dynamically typed language was "safer" because it would choose the "right" type (in your example, an arbitrary-pecision integer) automatically. As you can see from the above sample, it sometimes picks the "wrong" type, too. Now you tell me that this doesn't count, because I should have told Python what type to use. But shouldn't that apply to the Java binary-search example, too? I mean, you could have told Java to used a 64-bit or arbitrary-length integer type instead of a 32-bit integer (which would actually be equivalent to the Python code), so it would do the same thing as the Python binary search implementation. > ... > By the way, the equivalent Python code to your C# program gives on my > machine the very same result: > >>> x = 10001.0; x /= 100; x -= 100; print x > 0.01 Try entering "x" in the interpreter, and read up about the difference between str() and repr(). > > > Even if you used "from __future__ import division", it would actually > > return "0.010000000000005116", which, depending on the context, may > > still be an intolerable error. > > With from __future__ import division, I also get 0.01 printed. Anyway, > if there are small discrepancies then these have nothing to do with > Python but rather with the underlying floating-point hardware and C > library, the way how you print the value and the fact that 0.01 can > principally not be stored exactly as a float (nor as a C# decimal), only > as a Python Decimal. The is OT, but what makes you think a C# decimal can't store 0.01? > > I can even think of an example where C's (and Java's) bounded ints are > > the right choice, while Python's arbitraty-precision math isn't: > > Assume you get two 32-bit integers containing two time values (or > > values from an incremental encoder, or counter values). How do you > > find out how many timer ticks (or increments, or counts) have occured > > between those two values, and which one was earlier? In C, you can > > just write: > > > > long Distance(long t1, long t0) { return t1-t0; } > > > > And all the wraparound cases will be handled correctly (assuming there > > have been less than 2^31 timer ticks between these two time values). > > "Distance" will return a positive value if t1 was measured after t0, a > > negative value otherwise, even if there's been a wraparound in > > between. Try the same in Python and tell me which version is simpler! > > First of all, the whole problem only arises because you are using a > statically typed counter ;-) And it only is easy in C when your counter > has 32 bits. But what about a 24 bit counter? Easy, multiply it with 256 and it's a 32-bit counter ;-) Fortunately, 24-bit-counters are quite rare. 16-bit or 32-bit counters on the other hand are quite common, especially when you're working close to the hardware (where C is at home). All I wanted to point out is that bounded integers do have their advantages, because some people in this thread apparently have never stumbled over them. From cito at online.de Sun Jun 4 23:14:22 2006 From: cito at online.de (Christoph Zwerschke) Date: Sun, 04 Jun 2006 23:14:22 +0200 Subject: Python less error-prone than Java In-Reply-To: <1149453000.162259.105090@y43g2000cwc.googlegroups.com> References: <1149424883.529756.13700@j55g2000cwa.googlegroups.com> <1149453000.162259.105090@y43g2000cwc.googlegroups.com> Message-ID: nikie wrote: > Hm, then I probably didn't get your original point: I thought your > argument was that a dynamically typed language was "safer" because it > would choose the "right" type (in your example, an arbitrary-pecision > integer) automatically. No, my point was not to make a general statement. It just stumbled over that example and said to myself "that wouldn't have happend with Python." And I thought it might be interesting for people on c.l.p as well. That was all. > As you can see from the above sample, it > sometimes picks the "wrong" type, too. Now you tell me that this > doesn't count, because I should have told Python what type to use. Yes. Python did not "pick" that type - you explicitely said that x should an int by setting x = 10001. > I mean, you could have told Java to used a 64-bit or arbitrary-length > integer type instead of a 32-bit integer (which would actually be > equivalent to the Python code), so it would do the same thing > as the Python binary search implementation. Right, but then Java would do all index operations in that type, even for very small arrays when it's not necessary. That's why people probably don't do it. > The is OT, but what makes you think a C# decimal can't store 0.01? A C# data type summary gave me the impression that it was just a more accurate but still binary floating point type. But you're right, the name "decimal" should have given me a clue that it uses base 10 ;-) So sorry for the confusion. Forget what I wrote about float. I should have corretly written that the equivalent to the C# statement decimal x = 10001; is the following Python statement x = Decimal(10001) If you do the equivalent thing, Python will give the same result as C#. > All I wanted to point out is that bounded integers do have their > advantages, because some people in this thread apparently have > never stumbled over them. Sure, I did not want to deny that. The main advantages are speed, and dealing with hardware related issues. Your Distance function in C is of course much faster than my Python implementation. Surely I wouldn't want to write a device driver in Python. -- Christoph From martin at v.loewis.de Mon Jun 5 10:22:27 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 05 Jun 2006 10:22:27 +0200 Subject: Python less error-prone than Java In-Reply-To: References: <1149424883.529756.13700@j55g2000cwa.googlegroups.com> Message-ID: <4483E9C3.6090207@v.loewis.de> Christoph Zwerschke wrote: > Anyway, in Python, you would first define: > > def wrap(x, at=1<<31): > if x < -at: > x += at*2 > elif x >= at: > x -= at*2 > return x > > Then, the Python program would be as simple: > > Distance = lambda t1,t0: wrap(t1-t0) In Python 2.4 and later, you could write def Distance(t1, t0, maxint=(1<<32)-1): return (t1-t0) & maxint Like your code, this also extends to 24-bit integers or 64-bit integers. Regards, Martin From cito at online.de Mon Jun 5 11:59:36 2006 From: cito at online.de (Christoph Zwerschke) Date: Mon, 05 Jun 2006 11:59:36 +0200 Subject: Python less error-prone than Java In-Reply-To: <4483E9C3.6090207@v.loewis.de> References: <1149424883.529756.13700@j55g2000cwa.googlegroups.com> <4483E9C3.6090207@v.loewis.de> Message-ID: Martin v. L?wis wrote: > In Python 2.4 and later, you could write > > def Distance(t1, t0, maxint=(1<<32)-1): > return (t1-t0) & maxint No, this function behaves differently. It never returns a negative value. The only difference in Python 2.4 is that 1<<32 was 0 before. -- Christoph From no at spam.please Sun Jun 4 16:07:34 2006 From: no at spam.please (D H) Date: Sun, 04 Jun 2006 09:07:34 -0500 Subject: Python less error-prone than Java In-Reply-To: References: Message-ID: Christoph Zwerschke wrote: > > See the following web page if you dont find it ;-) > http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html The point of that is that it did fail. It threw an ArrayIndexOutOfBoundsException exception. But it was just luck that happened. Unfortunately I don't think java and C# have integer overflow checking turned on by default. Take this longArithmetic benchmark here: http://www.cowell-shah.com/research/benchmark/code and a story about it here: http://www.osnews.com/story.php?news_id=5602&page=3 The java and C# versions are fast (15 seconds for me), BUT, they give the incorrect result because of an overflow error. The python version gives the correct result because it transparently changes the underlying types to handle the larger numbers, BUT this causes it to run over 20X slower than Java or C#. It takes 10 minutes to complete in python, not 15 seconds. With psyco, it takes 5 minutes. So to say the story you pointed out shows that python is superior is a matter of perspective. Yes, python gave the correct result by silently changing the underlying types to longs, and that is what I would expect of a scripting language. But the price is speed. In both these cases, I would rather be made aware of the error in the code and fix it so I didn't have to suffer slowdowns. That is why in boo ( http://boo.codehaus.org/ ) luckily overflow checking is enabled by default, and it throws a overflow exception at runtime to tell you something is wrong with your code. When you then fix for that, you get the same 15 second time just like java and C#. From cga2000 at optonline.net Sun Jun 4 00:00:32 2006 From: cga2000 at optonline.net (cga2000) Date: Sat, 03 Jun 2006 18:00:32 -0400 Subject: Python & ncurses Message-ID: <20060603220032.GA18469@turki.gavron.org> Can anyone recommend a nice sample application that demonstrates the capabilities of python+ncurses and a clean/elegant UI? Thanks, cga From ldo at geek-central.gen.new_zealand Sun Jun 4 01:19:37 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 04 Jun 2006 11:19:37 +1200 Subject: So what would Python be? Message-ID: Just wondering... From aisaac0 at verizon.net Sun Jun 4 02:02:25 2006 From: aisaac0 at verizon.net (David Isaac) Date: Sun, 04 Jun 2006 00:02:25 GMT Subject: FreeImagePy and PIL Message-ID: I am just starting to think about image processing. What are the overlaps and differences in intended functionality between FreeImagePy and PIL? Thanks, Alan Isaac From michele.petrazzo at TOGLIunipex.it Mon Jun 5 09:42:09 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Mon, 05 Jun 2006 07:42:09 GMT Subject: FreeImagePy and PIL In-Reply-To: References: Message-ID: David Isaac wrote: > I am just starting to think about image processing. What are the > overlaps and differences in intended functionality between > FreeImagePy and PIL? > > Thanks, Alan Isaac > > http://tinyurl.com/m5kal For any other questions, I'm here :) Bye, Michele From alikakakhel at yahoo.com Sun Jun 4 02:46:49 2006 From: alikakakhel at yahoo.com (greenflame) Date: 3 Jun 2006 17:46:49 -0700 Subject: reordering elements of a list Message-ID: <1149382009.640607.217470@y43g2000cwc.googlegroups.com> I am trying to reorder elements of a list and I am stuck as to what might be the best way to approach this. I have a (main) list of elements and another (ordering) list (which is may shorter, but not longer than the main list) which contains the order in which I want the elements of the main list but only as far along as the length of the ordering list. This may be confusing so I will try to give an example. Suppose the main list is: mainlist = list('qwertyuiop') Suppose the ordering list is: orderinglist = [3, 4, 2, 1] Then I am looking for a function that will take mainlist and orderinglist as arguments and return the following list: ['e', 'r', 'w', 'q', 't', 'y', 'u', 'i', 'o', 'p'] Also by the way the main list is always going to be a list of strings and the ordering list will be a list of numbers. Also the largest number in orderinglist will always be equal to the length of orderinglist. I hope this makes any sense. Thanks for your help. From oliphant.travis at ieee.org Sun Jun 4 03:03:52 2006 From: oliphant.travis at ieee.org (Travis E. Oliphant) Date: Sat, 03 Jun 2006 19:03:52 -0600 Subject: reordering elements of a list In-Reply-To: <1149382009.640607.217470@y43g2000cwc.googlegroups.com> References: <1149382009.640607.217470@y43g2000cwc.googlegroups.com> Message-ID: greenflame wrote: > I am trying to reorder elements of a list and I am stuck as to what > might be the best way to approach this. I have a (main) list of > elements and another (ordering) list (which is may shorter, but not > longer than the main list) which contains the order in which I want the > elements of the main list but only as far along as the length of the > ordering list. This may be confusing so I will try to give an example. > > Suppose the main list is: mainlist = list('qwertyuiop') > > Suppose the ordering list is: orderinglist = [3, 4, 2, 1] > > Then I am looking for a function that will take mainlist and > orderinglist as arguments and return the following list: > > ['e', 'r', 'w', 'q', 't', 'y', 'u', 'i', 'o', 'p'] > > Also by the way the main list is always going to be a list of strings > and the ordering list will be a list of numbers. Also the largest > number in orderinglist will always be equal to the length of > orderinglist. I hope this makes any sense. Thanks for your help. > NumPy ( http://numeric.scipy.org ) can do this using element-based indexing on an array of strings. Your example: import numpy a = numpy.array('qwertyuiop','c') newlist = a[[2,3,1,0]+range(4,10)].tolist() print newlist Returns: ['e', 'r', 'w', 'q', 't', 'y', 'u', 'i', 'o', 'p'] But you can also do it with list comprehension pretty easily, so this is probably just a shameless plug for NumPy :-) -Travis From rbonvall at gmail.com Sun Jun 4 03:06:12 2006 From: rbonvall at gmail.com (Roberto Bonvallet) Date: Sat, 3 Jun 2006 21:06:12 -0400 Subject: reordering elements of a list In-Reply-To: <1149382009.640607.217470@y43g2000cwc.googlegroups.com> References: <1149382009.640607.217470@y43g2000cwc.googlegroups.com> Message-ID: <1908cb6b0606031806g5a98cbdax6c73c2ce1915bc3d@mail.gmail.com> 3 Jun 2006 17:46:49 -0700, greenflame : > Suppose the main list is: mainlist = list('qwertyuiop') > > Suppose the ordering list is: orderinglist = [3, 4, 2, 1] > > Then I am looking for a function that will take mainlist and > orderinglist as arguments and return the following list: > > ['e', 'r', 'w', 'q', 't', 'y', 'u', 'i', 'o', 'p'] >>> mainlist = list('qwertyuiop') >>> orderinglist = [3, 4, 2, 1] >>> [mainlist[i - 1] for i in orderinglist] + mainlist[len(orderinglist):] ['e', 'r', 'w', 'q', 't', 'y', 'u', 'i', 'o', 'p'] Best regards. -- Roberto Bonvallet From cito at online.de Sun Jun 4 04:06:30 2006 From: cito at online.de (Christoph Zwerschke) Date: Sun, 04 Jun 2006 04:06:30 +0200 Subject: reordering elements of a list In-Reply-To: <1149382009.640607.217470@y43g2000cwc.googlegroups.com> References: <1149382009.640607.217470@y43g2000cwc.googlegroups.com> Message-ID: greenflame wrote: > Suppose the main list is: mainlist = list('qwertyuiop') > Suppose the ordering list is: orderinglist = [3, 4, 2, 1] > > Then I am looking for a function that will take mainlist and > orderinglist as arguments and return the following list: > > ['e', 'r', 'w', 'q', 't', 'y', 'u', 'i', 'o', 'p'] > > Also by the way the main list is always going to be a list of strings > and the ordering list will be a list of numbers. Also the largest > number in orderinglist will always be equal to the length of > orderinglist. I hope this makes any sense. Thanks for your help. The following will do: map(lambda c, i: i and mainlist[i-1] or c, mainlist, orderinglist) -- Christoph From alikakakhel at yahoo.com Sun Jun 4 05:01:15 2006 From: alikakakhel at yahoo.com (greenflame) Date: 3 Jun 2006 20:01:15 -0700 Subject: reordering elements of a list In-Reply-To: <1149382009.640607.217470@y43g2000cwc.googlegroups.com> References: <1149382009.640607.217470@y43g2000cwc.googlegroups.com> Message-ID: <1149390075.653265.193370@j55g2000cwa.googlegroups.com> Thank you all for your replies. The only thing is I do not understand how the code is working. The following are more particular questions. Travis: Iam sorry, but I do not know what list comprehension is. Roberto: I do not understand the first half of the last line of your code. Also thank you for also teaching me to use '+' to append one list to another. This will be very useful for me. Christoph: I do not undertand the map method. Thanks again for all the help. :) From robert.kern at gmail.com Sun Jun 4 05:16:30 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 03 Jun 2006 22:16:30 -0500 Subject: reordering elements of a list In-Reply-To: <1149390075.653265.193370@j55g2000cwa.googlegroups.com> References: <1149382009.640607.217470@y43g2000cwc.googlegroups.com> <1149390075.653265.193370@j55g2000cwa.googlegroups.com> Message-ID: greenflame wrote: > Thank you all for your replies. The only thing is I do not understand > how the code is working. The following are more particular questions. Actually, these are statements, not questions. But anyways: > Travis: Iam sorry, but I do not know what list comprehension is. > Roberto: I do not understand the first half of the last line of your > code. That's what a list comprehension is. > Also thank you for also teaching me to use '+' to append one list > to another. This will be very useful for me. > Christoph: I do not undertand the map method. There is documentation on map() about halfway down this page: http://docs.python.org/lib/built-in-funcs.html Here's a tutorial which you should read: http://docs.python.org/tut/tut.html -- 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 rbonvall at gmail.com Mon Jun 5 02:05:01 2006 From: rbonvall at gmail.com (Roberto Bonvallet) Date: Sun, 4 Jun 2006 20:05:01 -0400 Subject: reordering elements of a list In-Reply-To: <1149390075.653265.193370@j55g2000cwa.googlegroups.com> References: <1149382009.640607.217470@y43g2000cwc.googlegroups.com> <1149390075.653265.193370@j55g2000cwa.googlegroups.com> Message-ID: <1908cb6b0606041705r308fea60rae2e0fb6adee3115@mail.gmail.com> greenflame : > Roberto: I do not understand the first half of the last line of your > code. [mainlist[i - 1] for i in orderinglist] is a list made with the elements of orderinglist, but instead of taking the actual value i from the list, the value that is taken is mainlist[i - 1]. If orderinglist is [3, 4, 2, 1], then [mainlist[i - 1] for i in orderinglist] is: [mainlist[3 - 1], mainlist[4 - 1], mainlist[2 - 1], mainlist[1 - 1]] Remember that indexing starts from 0. -- Roberto Bonvallet From alikakakhel at yahoo.com Mon Jun 5 18:53:20 2006 From: alikakakhel at yahoo.com (greenflame) Date: 5 Jun 2006 09:53:20 -0700 Subject: reordering elements of a list In-Reply-To: <1149382009.640607.217470@y43g2000cwc.googlegroups.com> References: <1149382009.640607.217470@y43g2000cwc.googlegroups.com> Message-ID: <1149526400.739601.178280@u72g2000cwu.googlegroups.com> Thanks all for your help! From jb at cascade-sys.com Sun Jun 4 03:36:14 2006 From: jb at cascade-sys.com (James J. Besemer) Date: Sat, 03 Jun 2006 18:36:14 -0700 Subject: Proposed new PEP: print to expand generators Message-ID: <4482390E.7060809@cascade-sys.com> I would like to champion a proposed enhancement to Python. I describe the basic idea below, in order to gage community interest. Right now, it's only an idea, and I'm sure there's room for improvement. And of course it's possible there's some serious "gotcha" I've overlooked. Thus I welcome any and all comments. If there's some agreement that this proposal is worth further consideration then I'll re-submit a formal document in official PEP format. Regards --jb PEP -- EXTEND PRINT TO EXPAND GENERATORS NUTSHELL I propose that we extend the semantics of "print" such that if the object to be printed is a generator then print would iterate over the resulting sequence of sub-objects and recursively print each of the items in order. E.g., print obj under the proposal would behave something like import types if type( obj ) == types.GeneratorType: for item in obj: print item, # recursive call print # trailing newline else: print obj # existing print behavior I know this isn't precisely how print would work, but I intentionally simplified the illustration to emphasize the intended change. Nevertheless, several points above expressly are part of this proposal (subject to discussion and possible revision): Print behavior does not change EXCEPT in the case that the object being printed is a generator. Enumerated items are printed with intervening spaces [alternatively: "" or "\n"]. An enumerated sequence ends with a newline [alternatively: "" or " "]. Iterators themselves could return iterators as elements, and the proposed change to print would recursively serialize any arbitrary "tree" of iterators. __str__() for complex user-defined objects then could return iterators, and arbitrarily complex structures could be printed out without glomming everything into a huge string -- only to throw it away in the end. I expect we likely also would want to modify str() itself to embody this serialization behavior. This additional change would support those cases where one actually does want the single large string in the end, say, to store into a UI widget. Still, the string would be constructed once at the end, much more efficiently than by building a bunch of smaller, intermediate strings. Then, in an abstract sense, we would not be changing print at all -- the new semantics would be embodied in the change to str(). However, in practice, we'd also want to modify print, as an important optimization for a more common use case. The present behavior (displaying, e.g., "") would still be available via print repr( generator ) Note that this behavior presently results from all three of: print generator print str( generator ) print repr( generator ) So, this proposal merely ascribes useful new semantics to the first two of three redundant language constructs. MOTIVATION With increasingly complex objects, the print representation naturally becomes more complex. In particular, when an object consists of a collection of sub-objects, it's natural for it's string representation to be defined recursively in terms of the sub-components' string representations, with some further indication of how they're held together. This is possible to do with the __str__ overload and the existing print semantics. However, existing semantics require constructing many otherwise unnecessary intermediate strings, and, as such, is grossly inefficient. Worse, each intermediate string is generally the catenation of several previous intermediaries, so the volume of intermediate results steadily increases throughout the conversion. Finally, the cost of string operations is proportional to the length of the strings in question, so I expect the overall cost increases significantly faster than in direct proportion to the size of the output (i.e. it's non-linear). E.g., instances of the following classes can become arbitrarily expensive to print out: def HtmlTable( object ): # ... def __str__( self ): return ( "\n" + "".join([ str( row ) for row in self.head ]) + "".join([ str( row ) for row in self.rows ]) + "\n" ) def HtmlRow( object ): # ... def __str__( self ): return ( "\n" + "".join([ str( cell ) for cell in self.cells ]) + "\n" ) def HtmlCell( object ): # ... def __str__( self ): return ( "\n" + "".join([ str( datum ) for datum in self.data ]) + "\n" ) Clearly, printing an arbitrary HtmlTable might require a LOT of unnecessary string manipulation. Using the proposed extension, the above example could be implemented instead as something like: def HtmlTable( object ): # ... def __str__( self ): yield "\n" for row in self.head: yield str( row ) for row in self.rows: yield str( row ) yield "\n" def HtmlRow( object ): # ... def __str__( self ): yield "\n" for cell in self.cells: yield str( cell ) yield "\n" def HtmlCell( object ): # ... def __str__( self ): yield "\n" for datum in self.data: yield str( datum ) yield "\n" With the new extension, the individual bits of data are simply output in the proper order, virtually eliminating unnecessary string operations, resulting in a huge performance improvement. In fact, in the common case where all of the leaf nodes are literal strings, then the entire HTML table (or page!) could be written out without any string manipulation -- the existing strings are simply written out from their present locations in memory! Furthermore, there's greater clarity and economy of expression in the proposed new method. The primary motivation behind this proposal is to eliminate unnecessary overhead, while retaining all the convenience of the existing semantics of string representations of custom objects. While it's not 100% backwards compatible, it assigns a new meaning to one of several redundant and little-used, existing language constructs. ALTERNATIVES In lieu of the proposed change, users can define their own auxiliary function to generate the output. E.g.: def HtmlTable( object ): # ... def pr( self, stream=sys.stdout ): ">stream, str( self.attr ) print >>stream, ">\n" for row in self.head: print >>stream, row row in self.rows: print >>stream, row print >>stream, "" I myself have successfully used this technique in a variety of applications. Pro: Requires no changes to Python Con: The solution has to be "hand crafted" in each case, subject to user errors. The solution only works if user expressly maintains the convention throughout his class hierarchy. The solution is not interchangeable with objects from other authors. /// From roy at panix.com Sun Jun 4 04:02:29 2006 From: roy at panix.com (Roy Smith) Date: Sat, 03 Jun 2006 22:02:29 -0400 Subject: Proposed new PEP: print to expand generators References: Message-ID: In article , "James J. Besemer" wrote: > I propose that we extend the semantics of "print" such that if the object to > be printed is a generator then print would iterate over the resulting > sequence of sub-objects and recursively print each of the items in order. I believe the functionality you desire already exists, or something very close to it, in the pprint (pretty printer) module. From steven.bethard at gmail.com Sun Jun 4 04:42:25 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 03 Jun 2006 20:42:25 -0600 Subject: Proposed new PEP: print to expand generators In-Reply-To: References: Message-ID: James J. Besemer wrote: > I propose that we extend the semantics of "print" such that if the > object to be printed is a generator then print would iterate over the > resulting sequence of sub-objects and recursively print each of the > items in order. I don't feel like searching for the specific python-dev threads right now, but something like this has been suggested before (I think with a "%i" formatting code), and Guido felt strongly that the addition or removal of a simple print statement shouldn't change the behavior of the surrounding code. Consider code like:: items = get_generator_or_None() for item in items: do_something(item) Now let's say I insert a debugging line like:: items = get_generator_or_None() print "make sure this isn't None:", items for item in items: do_something(item) My debugging line now just broke the rest of my code. That's not good. The other reason I don't think this PEP should go forward (at least as it is) is that Python 3000 is already going to turn the print statement into a function (though the exact details of that function have not been hashed out yet). So adding extra cruft to the print statement is kind of wasted effort. STeVe From bdesth.quelquechose at free.quelquepart.fr Mon Jun 5 04:33:48 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 05 Jun 2006 04:33:48 +0200 Subject: Proposed new PEP: print to expand generators In-Reply-To: References: Message-ID: <44836870$0$10284$636a55ce@news.free.fr> James J. Besemer a ?crit : > (snip) > > PEP -- EXTEND PRINT TO EXPAND GENERATORS > > NUTSHELL > > I propose that we extend the semantics of "print" such that if the > object to be printed is a generator then print would iterate over the > resulting sequence of sub-objects and recursively print each of the > items in order. > Please, don't: from itertools import cycle def mygen(): return cycle('this is a very bad idea'.split()) From tjreedy at udel.edu Sun Jun 4 04:02:55 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 3 Jun 2006 22:02:55 -0400 Subject: Proposed new PEP: print to expand generators References: <4482390E.7060809@cascade-sys.com> Message-ID: "James J. Besemer" wrote in message news:4482390E.7060809 at cascade-sys.com... > I propose that we extend the semantics of "print" such that if the object > to > be printed is a generator then print would iterate over the resulting > sequence of sub-objects and recursively print each of the items in order. A generator is an iterator produced by a generator function rather than a class. What treat them differently? Iterating over an iterator is usually destructive. So you would be printing what it was but no longer is. This is why iterators are printed differently from sequences. Terry Jan Reedy From mwilson-to at sympatico.ca Sun Jun 4 17:42:04 2006 From: mwilson-to at sympatico.ca (Mel Wilson) Date: Sun, 04 Jun 2006 11:42:04 -0400 Subject: Proposed new PEP: print to expand generators In-Reply-To: References: <4482390E.7060809@cascade-sys.com> Message-ID: Terry Reedy wrote: > "James J. Besemer" wrote in message > news:4482390E.7060809 at cascade-sys.com... >> I propose that we extend the semantics of "print" such that if the object >> to >> be printed is a generator then print would iterate over the resulting >> sequence of sub-objects and recursively print each of the items in order. > Iterating over an iterator is usually destructive. So you would be > printing what it was but no longer is. This is why iterators are printed > differently from sequences. I guess the motivation is the case of people who would set up an iterator specifically to print from it. print-as-debug-aid would get badly broken by the proposal, and I'd find that painful. Mel. From tjreedy at udel.edu Sun Jun 4 21:09:32 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 4 Jun 2006 15:09:32 -0400 Subject: Proposed new PEP: print to expand generators References: <4482390E.7060809@cascade-sys.com> Message-ID: "Mel Wilson" wrote in message news:ibDgg.74$LV.7874 at news20.bellglobal.com... > I guess the motivation is the case of people who would set > up an iterator specifically to print from it. for i in gen: print i, print is rather trivial and gives one the option to control formatting however. tjr From nexu.jin at gmail.com Sun Jun 4 05:57:13 2006 From: nexu.jin at gmail.com (Nexu) Date: Sun, 04 Jun 2006 05:57:13 +0200 Subject: Hostmask matching Message-ID: <1149393433.5979.6.camel@localhost.localdomain> I'm trying to write a def to match a string tha