From gagsl-py2 at yahoo.com.ar Mon Feb 18 15:02:36 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 18 Feb 2008 18:02:36 -0200 Subject: Developing a Package with Sub Packages References: Message-ID: En Mon, 18 Feb 2008 16:23:28 -0200, Josh English escribi?: > When testing the package in idle, this results in > C:\Python25\Lib\idlelib > instead of the file. > The Data folder is created in this folder now. Works for me: main.py: from testpkg import a testpkg directory (a subdirectory somewhere in sys.path): testpkg\__init__.py: (empty file) testpkg\a.py: import os print __name__, __file__, os.path.abspath(os.path.dirname(__file__)) In IDLE: File -> Open, main.py. F5 (Run Module). Output: testpkg.a C:\APPS\PYTHON25\lib\site-packages\testpkg\a.pyc C:\APPS\PYTHON25\lib\site-packages\testpkg -- Gabriel Genellina From bborcic at gmail.com Sat Feb 16 18:57:26 2008 From: bborcic at gmail.com (Boris Borcic) Date: Sun, 17 Feb 2008 00:57:26 +0100 Subject: An idea for fast function composition In-Reply-To: <2c092327-38d0-4624-8b24-a8a8a414b078@d5g2000hsc.googlegroups.com> References: <2c092327-38d0-4624-8b24-a8a8a414b078@d5g2000hsc.googlegroups.com> Message-ID: castironpi at gmail.com wrote: > On Feb 16, 3:47 pm, Arnaud Delobelle wrote: >> Hi all, >> >> Recently there was a thread about function composition in Python (and >> this was probably not the first). The fast way to create a >> (anonymous) composite function >> >> f1 o f2 o ... o fn >> >> in Python is via >> >> lambda x: f1(f2(...fn(x)...)), >> >> but according to some this is neither the most compact nor the most >> readable. Below I define a 'compose' function such that the above can >> be written >> >> compose(f1, f2, ...., fn), >> >> the resulting function being as fast as the lambda version (or maybe >> faster?). 'getcomposer' is a helper function (which in most cases >> will amount to a dictionary lookup). >> >> ---------------------------------- >> def getcomposer(nfunc, _cache={}): >> "getcomposer(n) -> lambda f1, ..., fn:(lambda x: f1(...fn(x)...))" >> try: >> return _cache[nfunc] >> except KeyError: >> fnames = ['f%s' % i for i in range(nfunc)] >> call = ''.join('%s(' % f for f in fnames) >> args = ','.join(fnames) >> cstr = 'lambda %s:(lambda x:%sx%s)' % (args, call, ')'*nfunc) >> composer = _cache[nfunc] = eval(cstr) >> return composer >> >> def compose(*functions): >> "compose(f1, ..., fn) -> lambda x: f1(f2(...fn(x)...))" >> return getcomposer(len(functions))(*functions) >> >> # Test >> >> def double(x): return 2*x >> def square(x): return x**2 >> def succ(x): return x+1 >> >> f1 = compose(double, square, succ, float) >> f2 = lambda x: double(square(succ(float(x)))) >> >> def benchmark(f, n=1000000): >> from time import time >> from itertools import imap >> t0 = time() >> for _ in imap(f1, xrange(n)): pass >> t1 = time() >> return t1-t0 >> >> print 'compose', benchmark(f1) >> print 'lambda ', benchmark(f2) >> ---------------------------------- >> >> marigold:python arno$ python -i simple_compose.py >> compose 1.84630298615 >> lambda 1.86365509033 >> >>> import dis >> >>> dis.dis(f1) >> 1 0 LOAD_DEREF 0 (f0) >> 3 LOAD_DEREF 3 (f1) >> 6 LOAD_DEREF 1 (f2) >> 9 LOAD_DEREF 2 (f3) >> 12 LOAD_FAST 0 (x) >> 15 CALL_FUNCTION 1 >> 18 CALL_FUNCTION 1 >> 21 CALL_FUNCTION 1 >> 24 CALL_FUNCTION 1 >> 27 RETURN_VALUE >> >>> dis.dis(f2) >> 23 0 LOAD_GLOBAL 0 (double) >> 3 LOAD_GLOBAL 1 (square) >> 6 LOAD_GLOBAL 2 (succ) >> 9 LOAD_GLOBAL 3 (float) >> 12 LOAD_FAST 0 (x) >> 15 CALL_FUNCTION 1 >> 18 CALL_FUNCTION 1 >> 21 CALL_FUNCTION 1 >> 24 CALL_FUNCTION 1 >> 27 RETURN_VALUE >> >> f1 and f2 are almost exaclty the same but array lookups (LOAD_DEREFs) >> in f1 replace dictionary lookups (LOAD_GLOBALs) in f2. A C version of >> 'compose' could easily be written that doesn't require the use of a >> python lambda-function (as created by 'getcomposer'). >> >> -- >> Arnaud > > def compose( funcs ): > def reccompose( *args ): > return compose( funcs[:-1] )( funcs[-1]( *args ) ) if funcs else > funcs[0]( *args ) > return reccompose >>> def compose( *funcs ): def reccompose( *args ): return compose( funcs[:-1] )( funcs[-1]( *args ) ) if funcs else funcs[0]( *args ) return reccompose >>> f3 = compose(double, square, succ, float) >>> import dis >>> dis.dis(f3) 3 0 LOAD_DEREF 0 (funcs) 3 JUMP_IF_FALSE 33 (to 39) 6 POP_TOP 7 LOAD_GLOBAL 0 (compose) 10 LOAD_DEREF 0 (funcs) 13 LOAD_CONST 1 (-1) 16 SLICE+2 17 CALL_FUNCTION 1 20 LOAD_DEREF 0 (funcs) 23 LOAD_CONST 1 (-1) 26 BINARY_SUBSCR 27 LOAD_FAST 0 (args) 30 CALL_FUNCTION_VAR 0 33 CALL_FUNCTION 1 36 JUMP_FORWARD 14 (to 53) >> 39 POP_TOP 40 LOAD_DEREF 0 (funcs) 43 LOAD_CONST 2 (0) 46 BINARY_SUBSCR 47 LOAD_FAST 0 (args) 50 CALL_FUNCTION_VAR 0 >> 53 RETURN_VALUE Mmmhhh... From matiassurdi at gmail.com Tue Feb 19 10:07:07 2008 From: matiassurdi at gmail.com (Matias Surdi) Date: Tue, 19 Feb 2008 16:07:07 +0100 Subject: matiassurdi@gmail.com Message-ID: test From volcimaster at gmail.com Tue Feb 12 13:27:10 2008 From: volcimaster at gmail.com (Warren Myers) Date: Tue, 12 Feb 2008 13:27:10 -0500 Subject: dream hardware In-Reply-To: References: Message-ID: A Cray? What are you trying to do? "dream" hardware is a very wide question. WMM On Feb 12, 2008 1:05 PM, wrote: > What is dream hardware for the Python interpreter? > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://warrenmyers.com "God may not play dice with the universe, but something strange is going on with the prime numbers." --Paul Erd?s "It's not possible. We are the type of people who have everything in our favor going against us." --Ben Jarhvi, Short Circuit 2 From ivanlan9 at gmail.com Fri Feb 15 13:05:02 2008 From: ivanlan9 at gmail.com (Ivan Van Laningham) Date: Fri, 15 Feb 2008 11:05:02 -0700 Subject: Solve a Debate In-Reply-To: <47B5C799.2030403@tim.thechases.com> References: <47B5C799.2030403@tim.thechases.com> Message-ID: Hi All-- Lookup tables are always significantly faster than a bunch of ifs. Metta, Ivan On Fri, Feb 15, 2008 at 10:10 AM, Tim Chase wrote: > > Ok the problem we had been asked a while back, to do a programming > > exercise (in college) > > That would tell you how many days there are in a month given a > > specific month. > > > > Ok I did my like this (just pseudo): > > > > If month = 1 or 3 or etc .... > > noDays = 31 > > Elseif month = 4 or 6 etc .... > > noDays = 30 > > Else > > noDays = 29 > > (we didn't have to take into account a leap year) > > > > He declared an array and assigned the number of days in a month to its > > own element in an array. Now > > I realise that in this example it would not make a difference in terms > > of efficiency, but it is my belief that if > > there is more data that needed to be assigned(i.e. a couple megs of > > data) it would be simpler (and more efficient) to > > do a compare rather then assigning all that data to an array, since > > you are only going to be using 1 value and the rest > > of the data in the array is useless. > > > > What are everyone else's thoughts on this? > > Well, the standard library offers its opinion: > > >>> import calendar > >>> calendar.mdays > [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] > >>> month = 2 > >>> calendar.mdays[month] > 28 > > If you want the actual number of days, taking leap-years into > consideration > > >>> calendar.monthrange(2008,2)[1] > 29 > >>> calendar.monthrange(2007,2)[1] > 28 > > So the answer is "mu"...let Python do the work for you :) > > -tkc > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Ivan Van Laningham God N Locomotive Works http://www.pauahtun.org/ http://www.python.org/workshops/1998-11/proceedings/papers/laningham/laningham.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Feb 18 12:54:23 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 18 Feb 2008 18:54:23 +0100 Subject: Python 3.0 In-Reply-To: References: <27CC3060AF71DA40A5DC85F7D5B70F38026E5A52@AWMAIL04.belcan.com> <895f1790802151602r354bffb4pcca979c9316fecf8@mail.gmail.com> <27CC3060AF71DA40A5DC85F7D5B70F38026E5A7F@AWMAIL04.belcan.com> <895f1790802151644q70c6cec6k946b4185cb2ddc13@mail.gmail.com> Message-ID: <47b9c5f9$0$3569$426a34cc@news.free.fr> Blubaugh, David A. a ?crit : > Is there a logical reason why Python 3 is not backwards compatible? Yes : cleaning up some cruft and warts accumulated from the years. From tandonmiir at gmail.com Mon Feb 25 02:33:59 2008 From: tandonmiir at gmail.com (Allen Peloquin) Date: Sun, 24 Feb 2008 23:33:59 -0800 (PST) Subject: Function Overloading and Python Message-ID: I have a personal project that has an elegant solution that requires both true multiple inheritance of classes (which pretty much limits my language choices to C++ and Python) and type-based function overloading. Now, while this makes it sound like I have to resign myself to C++, which I am not a fan of writing, I have resisted thus far. Who wants to manage their own memory? No, I have fallen in love with Python, and so come asking for help. I have a very large multiple inheritance tree that will be frequently extended as my project goes on. Let us call these "type A" classes. I also have a moderately sized single inheritance tree whose task is to match sets of "type A" parameters in a function. Let us call these "type B" classes. "Type Bs" have one function, which is extended with each new child, and overloaded to match varying combinations of "Type As." The reason for this is code-reuse and eventual matching with common "type A" parents. Now, what are my options in Python to dispatch unique code based on the permutations of "type A" classes without code repetition? Such as, where in C++... class B { fun(A x, A y, A z)... fun(A1 x, A y, A z)... } class B1 { fun(A1 x, A y, A z)... } Such that any previous behavior is inherited, but behaves polymorphically because of the single function name. B1.fun(A(x), A(y), A(z)) == B.fun(A(x), A(y), A(z)) but B1.fun(A1(x), A(y), A(z) != B.fun(A1(x), A(y), A(z)) Is there a data-structure solution or third party module that would mimic this behavior? PEP 3124 got my hopes up, but I was let down when it was deferred. Thank you for your time. From http Tue Feb 26 16:04:58 2008 From: http (Paul Rubin) Date: 26 Feb 2008 13:04:58 -0800 Subject: How about adding rational fraction to Python? References: <0d1955fc-762c-44e1-a5d8-372c71458455@p25g2000hsf.googlegroups.com> <36204e6f-0d82-449b-8ca5-c819ace9a55a@p73g2000hsd.googlegroups.com> <9503b14b-7bd5-42b4-b3f7-673d0ebd7feb@c33g2000hsd.googlegroups.com> <602ac27c-4aaa-49b2-bee2-1e0e0c705983@i7g2000prf.googlegroups.com> <1204034122.3318.3.camel@aalcdl07.lib.unc.edu> <20080226100824.fdc81ac7.darcy@druid.net> <1204051178.4191.11.camel@aalcdl07.lib.unc.edu> <20080226135152.6991f09b.darcy@druid.net> <1204053380.5087.7.camel@aalcdl07.lib.unc.edu> <7xejaz4exv.fsf@ruckus.brouhaha.com> Message-ID: <7xk5kra0p1.fsf@ruckus.brouhaha.com> "D'Arcy J.M. Cain" writes: > > http://en.wikipedia.org/wiki/Natural_number > Recheck the context. I was talking about the natural result, not > natural numbers. The natural result of doing arithmetic with natural numbers is more natural numbers. From lalitkrishna at gmail.com Wed Feb 20 17:03:04 2008 From: lalitkrishna at gmail.com (Lalit) Date: Wed, 20 Feb 2008 14:03:04 -0800 (PST) Subject: syntax error in python Message-ID: <89d4c968-e85f-48a8-9710-f44a1f748eee@c33g2000hsd.googlegroups.com> Hi I am executing following commands. >>> test = os.path.isfile('c:\\src\\kasjdfl.txt') >>> print test True ------------working fine but for below statement it is giving syntax error. >>> if (os.path.isfile('c:\\src\\kasjdfl.txt')) SyntaxError: invalid syntax any idea what is incorrect in my syntax From MartinRinehart at gmail.com Mon Feb 18 10:39:03 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Mon, 18 Feb 2008 07:39:03 -0800 (PST) Subject: Linux/Python Issues References: <8456cf3b-19e6-4695-9cbf-5f345b57e59b@e60g2000hsh.googlegroups.com> Message-ID: Paul Boddie wrote: > Here's one page which probably tells you stuff you already know: > > http://wiki.python.org/moin/BeginnersGuide/Download Thank you! It says I need Python (which I've got) and the Python-devel package, which sounds like it might include Tkinter and IDLE. Now if only I knew where to get the Python-devel package ... From david.car7 at gmail.com Tue Feb 5 21:59:48 2008 From: david.car7 at gmail.com (david.car7 at gmail.com) Date: Tue, 5 Feb 2008 18:59:48 -0800 (PST) Subject: Using a class as a structure/container Message-ID: <31f9058a-60a9-47b5-9c05-bddb31d2d04c@u10g2000prn.googlegroups.com> Is it appropriate to use a class as a simple container in order to access attributes using a series of dot operators? Is their a more Pythonic way of doing this? For instance, I have a "container" class which is never instantiated directly, but only through another class. Access to certain attributes would be something like: main_class.a.b.x where row and v1 are instances of the container class which are instantianted by main_class. I know I can use dictionaries, but this syntax is a little clearer as long as the number of dot operators is not too lengthy. Some code would be something like: class container(object): def __init__(self): pass class main_class(object): def __init__(self): self.a = container() settatr(self.a, 'b', container()) settatr(self.a.b, 'x', 2) Thanks in advance. From steve at holdenweb.com Mon Feb 18 12:51:54 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 18 Feb 2008 12:51:54 -0500 Subject: Python 3.0 In-Reply-To: <27CC3060AF71DA40A5DC85F7D5B70F38026E5E6E@AWMAIL04.belcan.com> References: <27CC3060AF71DA40A5DC85F7D5B70F38026E5A52@AWMAIL04.belcan.com> <895f1790802151602r354bffb4pcca979c9316fecf8@mail.gmail.com> <27CC3060AF71DA40A5DC85F7D5B70F38026E5A7F@AWMAIL04.belcan.com> <895f1790802151644q70c6cec6k946b4185cb2ddc13@mail.gmail.com> <27CC3060AF71DA40A5DC85F7D5B70F38026E5E6E@AWMAIL04.belcan.com> Message-ID: Blubaugh, David A. wrote: > Is there a logical reason why Python 3 is not backwards compatible? > Yes. For a long time now the next *major* release of Python has been flagged as one which will take the opportunity to remove several design flaws from the original language and add features and syntax that couldn't be added as long as backwards compatibility was maintained. There are, however, significant features in the 2.6 CPython implementation that will assist in migration, including an (optional) warning mode for usages that would cause problems in 3.0 and a tool that will migrate code that doesn't get flagged with warnings through to Python 3.0. So, in summary: 2.6 is the bridge to Python 3.0, and if you use it you won't have too much trouble migrating when the time comes. Note that Python 3.0 is currently at alpha2, and that even when it is released the "preferred" version will be 2.6. The early adopters will beat the snot out of 3.0, and us ordinary folk will probably not be ready to move until 3.1 or thereabouts. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From brian at briansmith.org Sat Feb 16 18:39:48 2008 From: brian at briansmith.org (Brian Smith) Date: Sat, 16 Feb 2008 15:39:48 -0800 Subject: Is there a way to "link" a python program from several files? In-Reply-To: <61p8tiF202j8lU1@mid.uni-berlin.de> References: <61or3kF1ssn8aU1@mid.uni-berlin.de> <61p8tiF202j8lU1@mid.uni-berlin.de> Message-ID: <002201c870f5$387c5570$6501a8c0@T60> Diez B. Roggisch wrote: > Brian Smith wrote: > > I would be interested in a program that can combine > > multiple modules into a single module, which removes > > all the inter-package imports and fixes other > > inter-module references, like Haskell > > All-in-One does for Haskell: > > http://www.cs.utah.edu/~hal/HAllInOne/index.html > > won't happen for python. python relies heavily on > modules/packages being namespaces. So does Haskell. Haskell All-In-One handles that by renaming every top-level artifact. > Why would you want such a beast anyway? If it's about > single-file-distribution, that is solved by some of the above > mentioned tools - or even not desired anyway (say OS X bundles) I want to package a complex WSGI application into a single CGI script, so that users can copy the script into some CGI-enabled directory and have it work without any further configuration, and so that it runs faster (especially when the file is on NFS). If it is possible to run an egg as a CGI (without modifying the web server configuration file), then that would work as well. - Brian From http Mon Feb 25 18:47:27 2008 From: http (Paul Rubin) Date: 25 Feb 2008 15:47:27 -0800 Subject: Python code for 2.5 and 2.4? References: <28a84535-483d-461d-828d-bb9a38be19f0@v3g2000hsc.googlegroups.com> <90aa62f8-ae45-485f-b847-106bb8950a88@71g2000hse.googlegroups.com> <7xpruktylj.fsf@ruckus.brouhaha.com> <2912ad02-085e-4b0e-a63d-7b10155b376b@d4g2000prg.googlegroups.com> Message-ID: <7xve4cr434.fsf@ruckus.brouhaha.com> Arnaud Delobelle writes: > Ok. In that case, the following is probably faster (in fact for long > iterables it may be equivalent to the builtin all): > > from itertools import ifilterfalse ... Nice. From ndbecker2 at gmail.com Thu Feb 21 13:53:24 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Thu, 21 Feb 2008 13:53:24 -0500 Subject: can't set attributes of built-in/extension type References: Message-ID: 7stud wrote: > On Feb 21, 11:19?am, Neal Becker wrote: >> I'm working on a simple extension. ?Following the classic 'noddy' >> example. >> >> In [15]: cmplx_int32 >> Out[15]: >> >> Now I want to add an attribute to this type. ?More precisely, I want a >> class attribute. >> >> cmplx_int32.test = 0 >> --------------------------------------------------------------------------- >> TypeError ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Traceback (most recent call >> last) >> >> /home/nbecker/numpy/ in () >> >> TypeError: can't set attributes of built-in/extension >> type 'numpy.cmplx_int32' >> >> What am I missing? > > > class Dog(object): > def __setattr__(self, attr, val): > print "TypeError: can't set attributes of built-in/extension" > print "type 'Dog.cmplx_int32'" > > d = Dog() > d.test = 0 > > --output:-- > TypeError: can't set attributes of built-in/extension > type 'Dog.cmplx_int32' Not quite, I'm setting a class attribute, not an attribute on an instance. From gherron at islandtraining.com Mon Feb 11 10:55:25 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 11 Feb 2008 07:55:25 -0800 Subject: Python equivt of __FILE__ and __LINE__ In-Reply-To: <1pudnQHrDeRBhi3anZ2dnUVZ8uudnZ2d@bt.com> References: <1pudnQHrDeRBhi3anZ2dnUVZ8uudnZ2d@bt.com> Message-ID: <47B06FED.6030707@islandtraining.com> Bill Davy wrote: > Writing a quick and dirty assembler and want to give the user the location > of an error. The "assembly language" is Python. If the user wants to > generat some object code they write something like: > > Label(LoopLable) > Load(R4) > Dec() > JNZ(LoopLabel) > > I can use Python to do all the expression evalutaion, conversion from Python > FP to target FP, include files, macros (done as function definitions). The > functions like Load() generate the approproyte object code. > > So, for example, when a label is defined or referenced, I save the File,Line > so if there is not exactly one defintion or no references, I can report the > file location(s) to be considered. In the example, I would want to report > that LoopLable is not referenced, and LoopLabel is not defined. > > TIA, > Bill > > PS www.SynectixLtd.com is not relevant > > > You *can* get at that kind of information: The traceback module has a function called "extract_stack" which can give you a pointer to the whole execution stack. From that can be generated all the usual stuff you see in a traceback -- including file and line information. *How* you extract that stuff, I'll leave as an exercises for the reader. (Meaning I haven't a clue.) Gary Herron From george.sakkis at gmail.com Fri Feb 22 01:02:01 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 21 Feb 2008 22:02:01 -0800 (PST) Subject: Return value of an assignment statement? References: <6d945394-739e-4c47-ad71-faaab8f9d566@34g2000hsz.googlegroups.com> <835a4fc1-f62a-4141-bca4-4e4f52519466@s37g2000prg.googlegroups.com> <5sudnTSXrZY0aCDanZ2dnUVZ_rKtnZ2d@comcast.com> <67ff8198-1d7d-4690-a9b6-42ebab2e642f@p73g2000hsd.googlegroups.com> <5MSdnceVGdH0iCPanZ2dnUVZ_vPinZ2d@comcast.com> <105cfd9f-0c50-4589-8bf6-9e16227dce75@s19g2000prg.googlegroups.com> Message-ID: On Feb 22, 12:26 am, Jeff Schwab wrote: > > On the other hand, "a = b" does always the same thing; unlike C++, '=' > > is not an operator and therefore it cannot be overriden by the class > > of 'a'. > > "Not an operator?" Then what is it? In this context, it's just the token used for the assignment statement. In short, if 'a' is an identifier, the statement means "bind the name 'a' to the object 'b' (in the local or global namespace)". It doesn't say anything about memory allocation, initialization or copying. The only case where assigning an identifier affects memory is the following [1]: """ The name is rebound if it was already bound. This may cause the reference count for the object previously bound to the name to reach zero, causing the object to be deallocated and its destructor (if it has one) to be called. """ HTH, George [1] http://docs.python.org/ref/assignment.html From steven.bethard at gmail.com Sat Feb 2 13:06:54 2008 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 02 Feb 2008 11:06:54 -0700 Subject: dict comprehension In-Reply-To: <47a320f3$0$25371$9b4e6d93@newsspool4.arcor-online.net> References: <22563849-ba45-4dfa-9782-78ef637be30f@s8g2000prg.googlegroups.com> <47a320f3$0$25371$9b4e6d93@newsspool4.arcor-online.net> Message-ID: Wildemar Wildenburger wrote: > Arnaud Delobelle wrote: >>> I believe both set and dict comprehensions will be in 3.0. >> >> Python 3.0a1+ (py3k:59330, Dec 4 2007, 18:44:39) >> [GCC 4.0.1 (Apple Inc. build 5465)] on darwin >> Type "help", "copyright", "credits" or "license" for more information. >>>>> {x*x for x in range(10)} >> {0, 1, 4, 81, 64, 9, 16, 49, 25, 36} >>>>> {x:x*x for x in range(10)} >> {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81} >> > OK, not bad. But I don't really see how this is better than the > generator approach. It's more than twice as fast: >>> setup = "items = range(10)" >>> timeit.Timer("dict((x, x * x) for x in items)", setup).timeit() 6.0559464959932114 >>> timeit.Timer("{x:x * x for x in items}", setup).timeit() 2.8347301821879682 It also doesn't build the unnecessary intermediate tuples: >>> def dict_genexp(items): ... return dict((x, x * x) for x in items) ... >>> def dict_comp(items): ... return {x:x * x for x in items} ... >>> dis.dis(dict_genexp.__code__.co_consts[1]) 2 0 LOAD_FAST 0 (.0) >> 3 FOR_ITER 21 (to 27) 6 STORE_FAST 1 (x) 9 LOAD_FAST 1 (x) 12 LOAD_FAST 1 (x) 15 LOAD_FAST 1 (x) 18 BINARY_MULTIPLY 19 BUILD_TUPLE 2 22 YIELD_VALUE 23 POP_TOP 24 JUMP_ABSOLUTE 3 >> 27 LOAD_CONST 0 (None) 30 RETURN_VALUE >>> dis.dis(dict_comp.__code__.co_consts[1]) 2 0 BUILD_MAP 0 3 DUP_TOP 4 STORE_FAST 1 (_[1]) 7 LOAD_FAST 0 (.0) >> 10 FOR_ITER 21 (to 34) 13 STORE_FAST 2 (x) 16 LOAD_FAST 1 (_[1]) 19 LOAD_FAST 2 (x) 22 LOAD_FAST 2 (x) 25 BINARY_MULTIPLY 26 ROT_TWO 27 LOAD_FAST 2 (x) 30 STORE_SUBSCR 31 JUMP_ABSOLUTE 10 >> 34 RETURN_VALUE STeVe From ndbecker2 at gmail.com Thu Feb 21 20:20:23 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Thu, 21 Feb 2008 20:20:23 -0500 Subject: can't set attributes of built-in/extension type References: Message-ID: Steve Holden wrote: > Neal Becker wrote: >> Steve Holden wrote: >> >>> Neal Becker wrote: >>>> 7stud wrote: >>>> >>>>> On Feb 21, 11:19 am, Neal Becker wrote: >>>>>> I'm working on a simple extension. Following the classic 'noddy' >>>>>> example. >>>>>> >>>>>> In [15]: cmplx_int32 >>>>>> Out[15]: >>>>>> >>>>>> Now I want to add an attribute to this type. More precisely, I want >>>>>> a class attribute. >>>>>> >>>>>> cmplx_int32.test = 0 >>>>>> --------------------------------------------------------------------------- >>>>>> TypeError Traceback (most recent call >>>>>> last) >>>>>> >>>>>> /home/nbecker/numpy/ in () >>>>>> >>>>>> TypeError: can't set attributes of built-in/extension >>>>>> type 'numpy.cmplx_int32' >>>>>> >>>>>> What am I missing? >>>>> class Dog(object): >>>>> def __setattr__(self, attr, val): >>>>> print "TypeError: can't set attributes of built-in/extension" >>>>> print "type 'Dog.cmplx_int32'" >>>>> >>>>> d = Dog() >>>>> d.test = 0 >>>>> >>>>> --output:-- >>>>> TypeError: can't set attributes of built-in/extension >>>>> type 'Dog.cmplx_int32' >>>> Not quite, I'm setting a class attribute, not an attribute on an >>>> instance. >>>> >>> Quite. The problem is that extension types' attributes are determined by >>> the layout of the object's slots and forever fixed in the C code that >>> implements them: the slots can't be extended, so there's no way to add >>> attributes. This is an efficiency feature: it would be *extremely* slow >>> to look up the basic types' attributes using late-binding (it would also >>> change the nature of the language somewhat, making it more like Ruby or >>> Self). >>> >>> So the reason you can't do what you want to is the same reason why you >>> can't add attribute to the built-in types (which are, of course, clearly >>> mentioned in the error message). >>> >>> >>> object.anyoldname = "You lose!" >>> Traceback (most recent call last): >>> File "", line 1, in >>> TypeError: can't set attributes of built-in/extension type 'object' >>> >>> >>> >>> If you look in typeobject.c you'll find this error message occurs when >>> the object's type isn't a PyHeapTypeObject (in other words, if it's one >>> of the built-in or extension types). >>> >> Thanks, but I'm a bit confused. After reading in my "Python in a >> Nutshell", I found that if after calling PyReady on my type object, if I >> use PyDict_SetItemString (my_type_obj.tp_dict,) >> >> That seems to work fine (which isn't exactly what it said in the Nutshell >> book, but close). >> I wanted to add an attribute to my type. Specifically, my type object is a static cmplx_int32_scalar_obj. After calling PyType_Ready (&cmplx_int32_scalar_obj), then I did PyDict_SetItemString (cmplx_int32_scalar_obj.tp_dict, "dtype", (PyObject*)d1); Now my type has the property: cmplx_int32.dtype dtype('cmplx_int32') Now, I do see that I still can't set it: cmplx_int32.dtype = 2 Traceback (most recent call last): File "", line 1, in TypeError: can't set attributes of built-in/extension type 'numpy.cmplx_int32' In this case, I don't need to. But I still don't know why I can have a python class and set class or instance attributes as I like, but this type acts differently. What would I need to do if I did want to allow arbitrary attributes to be set/added to my type? From larry.bates at websafe.com Fri Feb 8 12:15:58 2008 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 08 Feb 2008 11:15:58 -0600 Subject: keyword 'in' not returning a bool? In-Reply-To: References: Message-ID: c james wrote: > Try this > >>>> sample = {'t':True, 'f':False} >>>> 't' in sample > True >>>> type('t' in sample) > >>>> 't' in sample == True > False > > Why is this? Now try >>>> bool('t' in sample) == True > True > > Can someone explain what is going on? > Precedence. In: 't' in sample == True sample == True is evaluated first then 't' in that which is false you should write ('t' in sample) == True but that is unnecessary because t' in sample is easier to read and to code and less prone to this problem. -Larry From steve at holdenweb.com Mon Feb 25 11:48:12 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 25 Feb 2008 11:48:12 -0500 Subject: How about adding rational fraction to Python? In-Reply-To: <13s5r338rrtuq3f@corp.supernews.com> References: <198927a7-9478-42b3-a972-82049f0130ac@u10g2000prn.googlegroups.com> <1bc9bba7-dc7f-4cfe-8e1c-fa5901c9f556@n77g2000hse.googlegroups.com> <97f30679-483d-4751-9a6e-0858b36eb426@d4g2000prg.googlegroups.com> <649ac8a9-ae09-4e9b-85c2-f37043af21fd@28g2000hsw.googlegroups.com> <0d1955fc-762c-44e1-a5d8-372c71458455@p25g2000hsf.googlegroups.com> <36204e6f-0d82-449b-8ca5-c819ace9a55a@p73g2000hsd.googlegroups.com> <9503b14b-7bd5-42b4-b3f7-673d0ebd7feb@c33g2000hsd.googlegroups.com> <13s5r338rrtuq3f@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2008-02-25, Carl Banks wrote: > >> In other words, 3/4 in Python rightly yields a float > > Unless you're in the camp that believes 3/4 should yield the > integer 0. ;) > >> and not a rational. > No, that wouldn't be rational ;-) -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From mal at egenix.com Sat Feb 2 18:20:43 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Sun, 03 Feb 2008 00:20:43 +0100 Subject: fast method accessing large, simple structured data In-Reply-To: <98b871ed-3ef0-4be6-9533-359d83c6f64e@v17g2000hsa.googlegroups.com> References: <98b871ed-3ef0-4be6-9533-359d83c6f64e@v17g2000hsa.googlegroups.com> Message-ID: <47A4FACB.4090203@egenix.com> On 2008-02-02 21:36, agc wrote: > Hi, > > I'm looking for a fast way of accessing some simple (structured) data. > > The data is like this: > Approx 6 - 10 GB simple XML files with the only elements > I really care about are the and <article> ones. > > So what I'm hoping to do is put this data in a format so > that I can access it as fast as possible for a given request > (http request, Python web server) that specifies just the title, > and I return the article content. > > Is there some good format that is optimized for search for > just 1 attribute (title) and then returning the corresponding article? > > I've thought about putting this data in a SQLite database because > from what I know SQLite has very fast reads (no network latency, etc) > but not as fast writes, which is fine because I probably wont be doing > much writing (I wont ever care about the speed of any writes). > > So is a database the way to go, or is there some other, > more specialized format that would be better? Depends on what you want to search and how, e.g. whether a search for title substrings should give results, whether stemming is needed, etc. If all you want is a simple mapping of full title to article string, an on-disk dictionary is probably the way to go, e.g. mxBeeBase (part of the eGenix mx Base Distribution). For more complex search, you're better off with a tool that indexes the titles based on words, ie. a full-text search engine such as Lucene. Databases can also handle this, but they often have problems when it comes to more complex queries where their indexes no longer help them to speed up the query and they have to resort to doing a table scan - a sequential search of all rows. Some databases provide special full-text extensions, but those are of varying quality. Better use a specialized tool such as Lucene for this. For more background on the problems of full-text search, see e.g. http://www.ibm.com/developerworks/opensource/library/l-pyind.html -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Feb 03 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From AWasilenko at gmail.com Sat Feb 2 06:48:14 2008 From: AWasilenko at gmail.com (Adam W.) Date: Sat, 2 Feb 2008 03:48:14 -0800 (PST) Subject: Urllib keyerror, confused Message-ID: <234a77c8-8ef8-4289-813a-f66a43f38cb5@v46g2000hsv.googlegroups.com> I took this script: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/83208 And decided to try it out, it works when I first download a file, and when I try to resume a downloaded file, but if the file is already downloaded, and I expect to see the print "File already downloaded" message come up, I get a keyerror instead: Traceback (most recent call last): File "C:\Users\Adam\Desktop\ddd.py", line 26, in <module> if int(webPage.headers['Content-Length']) == existSize: File "C:\Python25\lib\rfc822.py", line 384, in __getitem__ return self.dict[name.lower()] KeyError: 'content-length' Why did the key disappear? Here is the code I used (a little modified but functionally the same): import urllib, os class myURLOpener(urllib.FancyURLopener): """Create sub-class in order to overide error 206. This error means a partial file is being sent, which is ok in this case. Do nothing with this error. """ def http_error_206(self, url, fp, errcode, errmsg, headers, data=None): pass loop = 1 dlFile = "Okidata_Digital_B4600_Black_and_White_Laser_PrinterlacDetail.jpg" existSize = 0 myUrlclass = myURLOpener() if os.path.exists(dlFile): outputFile = open(dlFile,"ab") existSize = os.path.getsize(dlFile) #If the file exists, then only download the remainder myUrlclass.addheader("Range","bytes=%s-" % (existSize)) else: outputFile = open(dlFile,"wb") webPage = myUrlclass.open("http://s3-external-1.amazonaws.com/ wootsaleimages/%s" % dlFile) #If the file exists, but we already have the whole thing, don't download again print "flyby" if int(webPage.headers['Content-Length']) == existSize: loop = 0 print "File already downloaded" numBytes = 0.0 numBytes += existSize while loop: data = webPage.read(8192) if not data: break outputFile.write(data) numBytes += len(data) print (float(numBytes/int(webPage.headers['Content-Length']))*100) webPage.close() outputFile.close() for k,v in webPage.headers.items(): print k, "=",v print "copied", numBytes, "bytes from", webPage.url raw_input("Cat") From castironpi at gmail.com Sat Feb 9 16:04:44 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 9 Feb 2008 13:04:44 -0800 (PST) Subject: C function in a Python context References: <4717e82c-0b92-4e05-8ab9-4c2e8fc2ad3f@s12g2000prg.googlegroups.com> Message-ID: <e7342bf0-93e1-4128-ad27-acaa1adadd23@q77g2000hsh.googlegroups.com> On Feb 9, 1:48?pm, castiro... at gmail.com wrote: > To write quick C things that Python won't do up to speed. ?So it's got > a redundancy. > > import ext > extA= ext.Ext() > extA[ 'enumfactors' ]= r""" > ? ? int enumfactors( int a, const char* sep ) { > ? ? ? ? int ret= 0, i; > ? ? ? ? for( i= 1; i<= a; i++ ) { > ? ? ? ? ? ? if( a% i== 0 ) { > ? ? ? ? ? ? ? ? ret+= 1; > ? ? ? ? ? ? ? ? if( i> 1 ) { > ? ? ? ? ? ? ? ? ? ? printf( "%s", sep ); > ? ? ? ? ? ? ? ? } > ? ? ? ? ? ? ? ? printf( "%i", i ); > ? ? ? ? ? ? } > ? ? ? ? } > ? ? ? ? printf( "\n" ); > ? ? ? ? return ret; > ? ? } > ? ? """, ("i","i","s") > > factorsn= extA.enumfactors( 209677683, ', ' ) > print( "%i factors total."% factorsn ) > > import sys > sys.exit() > > 1, 3, 23, 69, 131, 393, 3013, 9039, 23197, 69591, 533531, 1600593, > 3038807, 9116 > 421, 69892561, 209677683 > 16 factors total. '''Prototype implementation, slightly rigid. If anyone knows how to compile and link without intermediate object file, and from a string, memory, or stdin, let me know. Change first four lines. If you are not using gcc, look at regenpyd().''' compilercommand= 'c:/programs/mingw/bin/gcc' pythondll= 'python30' pythonpathinclude= 'c:/programs/python/include' pythonpathlibs= 'c:/programs/python/libs' class Ext: strctypes= { 'i': 'int', 's': 'const char*' } class ExtElem: def __init__( self, name, code, types ): self.name, self.code= name, code self.types= types def __init__( self ): self.__dict__[ 'exts' ]= [] def regenc( self ): extcode= open( 'extcode.c', 'w' ) wr= extcode.write wr( '#include <%s'% pythonpathinclude ) wr( '/Python.h>\n\n' ) for ext in self.exts: wr( ext.code ) wr( '\n' ) for ext in self.exts: wr( 'static PyObject *\n' ) wr( 'extcode_%s'% ext.name ) wr( '(PyObject *self, ' ) wr( 'PyObject *args) {\n' ) wr( '\t%s result;\n'% Ext.strctypes[ext.types[0]] ) for i, type in enumerate( ext.types[1:] ): wr( '\t%s arg%i;\n'% ( Ext.strctypes[type], i ) ) wr( '\tPyArg_ParseTuple(args, "' ) wr( ''.join( ext.types[1:] ) ) wr( '"' ) for i, type in enumerate( ext.types[1:] ): wr( ', &arg%i'% i ) wr( ' );\n' ) wr( '\tresult= %s( '% ext.name ) wr( ', '.join( [ 'arg%i'% i for i in range( len( ext.types[1:] ) ) ] ) ) wr( ' );\n' ) wr( '\treturn Py_BuildValue' ) wr( '( "%s", result );\n'% ext.types[0] ) wr( '}\n\n' ) wr( 'static PyMethodDef ExtcodeMethods[] = {\n' ) for ext in self.exts: wr( '\t{ "%s", extcode_%s, '% ( ext.name, ext.name ) ) wr( 'METH_VARARGS, "" },\n' ) wr( '\t{NULL, NULL, 0, NULL}\n' ) wr( '};\n\n' ) wr( 'PyMODINIT_FUNC\n' ) wr( 'initextcode(void) {\n' ) wr( '\t(void) Py_InitModule' ) wr( '("extcode", ExtcodeMethods);\n' ) wr( '}\n\n' ) extcode.close() def regenpyd( self ): import os, os.path if os.path.exists( 'extcode.pyd' ): os.remove( 'extcode.pyd' ) import subprocess retcompile= subprocess.call( '%s extcode.c -c -I%s'% ( compilercommand, pythonpathinclude ) ) assert not retcompile, 'Compiler error' retlink= subprocess.call( '%s -shared extcode.o -o extcode.pyd -L%s -l%s' % ( compilercommand, pythonpathlibs, pythondll ) ) assert not retlink, 'Linker error' os.remove( 'extcode.o' ) os.remove( 'extcode.c' ) def __setitem__( self, key, value ): code, types= value self.exts.append( Ext.ExtElem( key, code, types ) ) self.regenc() self.regenpyd() import extcode setattr( self, key, getattr( extcode, key ) ) From lists at cheimes.de Wed Feb 27 05:55:44 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 27 Feb 2008 11:55:44 +0100 Subject: Documentation - which format In-Reply-To: <8763waev98.fsf@benfinney.id.au> References: <0001HW.C3EA559A00413F8FB01AD9AF@news.individual.de> <87k5krdmtc.fsf@benfinney.id.au> <0001HW.C3EAC18C0045A69FB01AD9AF@news.individual.de> <8763waev98.fsf@benfinney.id.au> Message-ID: <fq3fjh$rsn$2@ger.gmane.org> Ben Finney wrote: > Yes, TTBOMK. The site hasn't been updated for a while, but I follow > the mailing list and activity continues on the code itself. Python 2.6 and newer are using reST for documentation, see http://docs.python.org/dev/ Christian From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Feb 15 03:34:31 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 15 Feb 2008 09:34:31 +0100 Subject: adding values to keys In-Reply-To: <34005f69-4031-4baf-8014-d209e818ec85@s19g2000prg.googlegroups.com> References: <34005f69-4031-4baf-8014-d209e818ec85@s19g2000prg.googlegroups.com> Message-ID: <47b54e56$0$16996$426a74cc@news.free.fr> Brandon a ?crit : > Hi all, > > I'm not sure if I'm calling the right method in a dictionary. I have: > > for k,v in dict.items(): don't use 'dict' as an identifier, this shadows the builtin dict type. > NT = k,range(alpha,omega) #where alpha and omega are > previously defined as 1 and 4, respectively > print NT If you don't care about the values, you should iterate directly over the keys - which is the default for dicts, ie: for key in somedict: print k Also, by convention, ALL_CAPS names denote (pseudo) symbolic constants. > which gives: > ('w', [0,1,2,3]) > ('x', [0,1,2,3]) > ('y', [0,1,2,3]) > ('z', [0,1,2,3]) and by that time, NT == ('z', [0,1,2,3]) > And now I want a master dictionary like: [{'w': [0],[1],[2],[3]}, > {'x': [0]...] This is a list of dicts, each one having a single key pointing to a tuple of four one-element lists. Are you *sure* this is *really* what you want ? > So I try: > > MT = {} this creates an empty dict instance... > MT.fromkeys(NT[0], range(alpha,omega)) this calls the classmethod dict.fromkeys() on the empty dict instance created by the previous statement, and discards the dict instance created by the call to fromkeys(). Also, since at this stage NT is ('z', [0,1,2,3]), NT[0] is 'z', so the dict created by fromkeys (and happily discarded) looked like: {'z': [0, 1, 2, 3]} > print MT > > but this only returns: > {} Indeed. You defined MT as an empty dict, didn't you ? > {} > {}... > > Anybody see what I'm doing wrong? Quite a lot of things actually, but the worst one is probably failing to read the FineManual(tm) !-) Assuming that you have a dict d, and want to build another dict with d keys and range(alpha,omega) for values, here's the solution: alpha = 0 omega = 4 # arbitrary values, just for the exemple d = dict(w=1, x=2, y=3, z=4) master = dict.fromkeys(d, range(alpha, omega)) print master => {'y': [0, 1, 2, 3], 'x': [0, 1, 2, 3], 'z': [0, 1, 2, 3], 'w': [0, 1, 2, 3]} Now note that this will associate each key of master with the *same* list instance, so: master['y'].append(42) >>> print master {'y': [0, 1, 2, 3, 42], 'x': [0, 1, 2, 3, 42], 'z': [0, 1, 2, 3, 42], 'w': [0, 1, 2, 3, 42]} which is perhaps not what you want !-) If you want distinct lists, dict.fromkeys is not the right method. You'd better use the default constructor, passing it a sequence of key,value tuples, ie: master = dict((k, range(0,4)) for k in d) print master => {'y': [0, 1, 2, 3], 'x': [0, 1, 2, 3], 'z': [0, 1, 2, 3], 'w': [0, 1, 2, 3]} master['y'].append(42) print master {'y': [0, 1, 2, 3, 42], 'x': [0, 1, 2, 3], 'z': [0, 1, 2, 3], 'w': [0, 1, 2, 3]} > Any advice is much appreciated. Ok: - read the FineManual(tm) - learn to use the interactive Python shell - read the FineManual(tm) - learn to use the help feature of the interactive Python shell - read the FineManual(tm) - read pep08 on naming conventions - read the FineManual(tm) !-) HTH From jeffober at gmail.com Mon Feb 4 08:06:40 2008 From: jeffober at gmail.com (Jeff) Date: Mon, 4 Feb 2008 05:06:40 -0800 (PST) Subject: Too many open files References: <47a70bd0$0$3908$426a74cc@news.free.fr> Message-ID: <500106b8-447d-41db-a99b-adc5ae00a223@z17g2000hsg.googlegroups.com> Why don't you start around 50 threads at a time to do the file writes? Threads are effective for IO. You open the source file, start a queue, and start sending data sets to be written to the queue. Your source file processing can go on while the writes are done in other threads. From miki.tebeka at gmail.com Wed Feb 20 22:51:49 2008 From: miki.tebeka at gmail.com (Miki) Date: Wed, 20 Feb 2008 19:51:49 -0800 (PST) Subject: unitests don't run under pdb References: <153b2666-bd64-48e9-beb2-d4e01e01d55b@z70g2000hsb.googlegroups.com> Message-ID: <0b08663d-59ea-4cc5-a94a-281fd76d30dd@p43g2000hsc.googlegroups.com> Hello Amit, > python testname.py : the unitests runs as usual and I get the > following results: > ---------------------------------------------------------------------- > Ran 2 tests in 0.024s > > OK > -------------------------------------------------------------------- > > However, if I do "python -m pdb testnames.py": I get > ython -m pdb testnames.py> /s/nd6/amit/pyiglu/testnames.py(1)<module>() > > -> import unittest > (Pdb) c > > ---------------------------------------------------------------------- > Ran 0 tests in 0.000s > > OK > ------------------------------------------------------------------- IIRC unittest checks the __main__ module for tests to run. Once you run python with "-m pdb" the __main__ module is pdb and not your script. HTH, -- Miki <miki.tebeka at gmail.com> http://pythonwise.blogspot.com From dickinsm at gmail.com Sun Feb 10 17:44:58 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Sun, 10 Feb 2008 14:44:58 -0800 (PST) Subject: Turn off ZeroDivisionError? References: <mailman.566.1202594651.9267.python-list@python.org> <f65a56e0-48c9-446a-8d09-4c87de87ae51@m34g2000hsb.googlegroups.com> <45349320-fe77-4581-ba88-064cc81667a3@e6g2000prf.googlegroups.com> <mailman.595.1202678380.9267.python-list@python.org> <13qusnn1ok8rr6f@corp.supernews.com> Message-ID: <7873e29b-57a5-448f-b102-f308af83f057@e25g2000prg.googlegroups.com> On Feb 10, 4:56?pm, Grant Edwards <gra... at visi.com> wrote: > Exactly. ?Espeically when Python supposedly leaves floating > point ops up to the platform. There's a thread at http://mail.python.org/pipermail/python-list/2005-July/329849.html that's quite relevant to this discussion. See especially the exchanges between Michael Hudson and Tim Peters in the later part of the thread. I like this bit, from Tim: "I believe Python should raise exceptions in these cases by default, because, as above, they correspond to the overflow and invalid-operation signals respectively, and Python should raise exceptions on the overflow, invalid-operation, and divide-by-0 signals by default. But I also believe Python _dare not_ do so unless it also supplies sane machinery for disabling traps on specific signals (along the lines of the relevant standards here). Many serious numeric programmers would be livid, and justifiably so, if they couldn't get non-stop mode back. The most likely x-platfrom accident so far is that they've been getting non-stop mode in Python since its beginning." Mark From pavlovevidence at gmail.com Wed Feb 20 20:34:43 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 20 Feb 2008 17:34:43 -0800 (PST) Subject: is this data structure build-in or I'll have to write my own class? References: <mailman.1016.1203513150.9267.python-list@python.org> Message-ID: <c71ffbe9-b71d-4214-9d6f-04e48ebc7288@n58g2000hsf.googlegroups.com> On Feb 20, 8:12 am, "Jorge Vargas" <jorge.var... at gmail.com> wrote: > I need a data structure that will let me do: > > - attribute access (or index) > - maintain the order (for iter and print) > - be mutable. > > in case there isn't one. I was thinking having a base class like Bunchhttp://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308and on > top of that keeping a list of the keys and pop/push to the list when > adding/deleting items. I don't like this idea because I'll have to > keep each key twice. (in the list and in __dict__, is this the only > way of doing it? OrderedDict is usually the term used here for this (not to be confused with SortedDict, which is a mapping type with identically sorted keys). It's asked for pretty often but no one's stepped up to implement one for the standard library. Carl Banks From castironpi at gmail.com Fri Feb 1 23:59:46 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 1 Feb 2008 20:59:46 -0800 (PST) Subject: functools possibilities Message-ID: <221cfae5-0114-4858-9ad6-127fe48e715d@d21g2000prf.googlegroups.com> 1. functools.partialpre: partialpre( f, x, y )( z )-> f( z, x, y ) 2. functools.pare: pare( f, 1 )( x, y )-> f( y ) 3. functools.parepre: parepre( f, 1 )( x, y )-> f( x ) 4. functools.calling_default: calling_default( f, a, DefaultA, b )-> f( a, <default 2rd arg, even if not None>, b ) From stefan.witzel at zvw.uni-goettingen.de Thu Feb 7 05:21:28 2008 From: stefan.witzel at zvw.uni-goettingen.de (Stefan Witzel) Date: Thu, 7 Feb 2008 10:21:28 +0000 (UTC) Subject: smtpd module References: <fobo15$j5n$1@gwdu112.gwdg.de> Message-ID: <foem38$6qk$1@gwdu112.gwdg.de> Stefan Witzel wrote: > Hello, > > the documentation of the smtpd module in the Python Library Reference > is very short, I think. Are there any examples available? Especially > I'm interested in the DebuggingServer. > > Thanks in advance. > > Stefan Sorry, I found the example - it's in the source file. Stefan From tandonmiir at gmail.com Mon Feb 25 02:48:28 2008 From: tandonmiir at gmail.com (Allen Peloquin) Date: Sun, 24 Feb 2008 23:48:28 -0800 (PST) Subject: Function Overloading and Python References: <ffa03c57-4b3d-4e37-82c1-f0f117acd981@28g2000hsw.googlegroups.com> <47C271E4.3050203@behnel.de> Message-ID: <8d9d3f48-b3d8-4f09-ab7b-7338a18d7d7d@q78g2000hsh.googlegroups.com> On Feb 24, 11:44 pm, Stefan Behnel <stefan... at behnel.de> wrote: > Allen Peloquin wrote: > > class B > > { > > fun(A x, A y, A z)... > > fun(A1 x, A y, A z)... > > } > > > class B1 > > { > > fun(A1 x, A y, A z)... > > } > > > Such that any previous behavior is inherited, but behaves > > polymorphically because of the single function name. > > Try something like this: > > class B(object): > def fun(x,y,z): > if isinstance(x, A1): > return self._fun(x,y,z) > # ... > > def _fun(x,y,z): > # ... > > class B1(B): > def _fun(x,y,z): > # ... > > Stefan The problem is that I want to reuse the code of the parent classes through inheritance, otherwise this would work fine. I am aware that because of the dynamic typing of Python, there currently is no type-based function overloading, so I'm looking for alternate solutions to my design problem. From kyosohma at gmail.com Mon Feb 25 15:47:59 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 25 Feb 2008 12:47:59 -0800 (PST) Subject: Python code for 2.5 and 2.4? References: <28a84535-483d-461d-828d-bb9a38be19f0@v3g2000hsc.googlegroups.com> Message-ID: <b5cb8335-8fc0-42f9-82da-a71b7a85a2fd@e60g2000hsh.googlegroups.com> On Feb 25, 2:40 pm, Joseph Turian <tur... at gmail.com> wrote: > I was given code that was written for python 2.5, and uses simple > functions like 'all' which are not present in 2.4 > > I want to make the code 2.4 compatible. What is the best way to do > this? > If I define function 'all', then won't I break 2.5 compatability? > > Thanks, > Joseph See http://docs.python.org/lib/built-in-funcs.html which shows the current built-ins for Python. It also shows an equivalent function for all() that should work in 2.4. You can do a check at the beginning of your file by importing the sys module. Something like this: <code> # untested import sys version = sys.version.split(' ')[0] if '2.5' not in version: # use custom all() script </code> HTH Mike From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Feb 25 04:00:49 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 25 Feb 2008 10:00:49 +0100 Subject: Function Overloading and Python In-Reply-To: <ffa03c57-4b3d-4e37-82c1-f0f117acd981@28g2000hsw.googlegroups.com> References: <ffa03c57-4b3d-4e37-82c1-f0f117acd981@28g2000hsw.googlegroups.com> Message-ID: <47c28344$0$7036$426a74cc@news.free.fr> Allen Peloquin a ?crit : > I have a personal project that has an elegant solution that requires > both true multiple inheritance of classes (which pretty much limits my > language choices to C++ and Python) and type-based function > overloading. > > Now, while this makes it sound like I have to resign myself to C++, > which I am not a fan of writing, I have resisted thus far. Who wants > to manage their own memory? No, I have fallen in love with Python, and > so come asking for help. (snip) > Now, what are my options in Python to dispatch unique code based on > the permutations of "type A" classes without code repetition? There are at least a couple type- or rule- based dispatch packages or receipes around. Googling for 'generic' or 'ruledispatch' etc... might give you a start. From fabiofz at gmail.com Mon Feb 4 12:42:18 2008 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Mon, 4 Feb 2008 15:42:18 -0200 Subject: Pydev 1.3.13 Released Message-ID: <cfb578b20802040942u53afe308l72c1d254208ffca0@mail.gmail.com> Hi All, Pydev and Pydev Extensions 1.3.13 have been released Details on Pydev Extensions: http://www.fabioz.com/pydev Details on Pydev: http://pydev.sf.net Details on its development: http://pydev.blogspot.com Release Highlights in Pydev Extensions: ----------------------------------------------------------------- * Debug Console: will print exceptions raised during the evaluation. * Debug Console: will print the result of the evaluation if a valid statement is sent (so, 'print' is not needed for simple evaluations anymore). Release Highlights in Pydev: ---------------------------------------------- * Outline view: working correctly again. * Keybinding conflict: Alt+shift+T+XXX refactoring keybindings are now only defined in the pydev scope. * Hyperlink: Using new hyperlink mechanism (added at Eclipse 3.3). What is PyDev? --------------------------- PyDev is a plugin that enables users to use Eclipse for Python and Jython development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny ------------------------------------------------------ Software Developer ESSS - Engineering Simulation and Scientific Software http://www.esss.com.br Pydev Extensions http://www.fabioz.com/pydev Pydev - Python Development Enviroment for Eclipse http://pydev.sf.net http://pydev.blogspot.com From skpeterson at nospam.please.ucdavis.edu Fri Feb 22 02:28:22 2008 From: skpeterson at nospam.please.ucdavis.edu (Sam Peterson) Date: Thu, 21 Feb 2008 23:28:22 -0800 Subject: distutils and data files References: <87odacmnc4.fsf@nospam.please.ucdavis.edu> <mailman.1000.1203496174.9267.python-list@python.org> Message-ID: <87zltto3ft.fsf@nospam.please.ucdavis.edu> Robert Bossy <Robert.Bossy at jouy.inra.fr> on Wed, 20 Feb 2008 09:29:12 +0100 didst step forth and proclaim thus: > Sam Peterson wrote: >> I've been googling for a while now and cannot find a good way to deal >> with this. >> >> I have a slightly messy python program I wrote that I've historically >> just run from the extracted source folder. I have pictures and sound >> files in this folder that this program uses. I've always just used >> the relative path names of these files in my program. >> >> Lately, I had the idea of cleaning up my program and packaging it with >> distutils, but I've been stuck on a good way to deal with these >> resource files. The package_data keyword seems to be the way to go, >> but how can I locate and open my files once they've been moved? In >> other words, what should I do about changing the relative path names? >> I need something that could work from both the extracted source >> folder, AND when the program gets installed via the python setup.py >> install command. >> > This seems to be a classic distutils question: how a python module > can access to data files *after* being installed? Man, I was afraid of that. Python is an awesome language, but this is yet another instance of seeing something in the standard library sucking. > The following thread addresses this issue: > http://www.gossamer-threads.com/lists/python/python/163159 > > Carl Banks' solution seems to overcome the problem: his trick is to > generate an additional configuration module with the relevant > informations from the distutil data structure. However it is quite an > old thread (2003) and I don't know if there has been progress made > since then, maybe the distutils module now incorporates a similar > mechanism. Not if the documentation for 2.5's got anything to say about it. If it does, it's well hidden. I think I'll kill the idea of using distutils for my program. It seems like distutils was primarily designed for modules and extensions. -- Sam Peterson skpeterson At nospam ucdavis.edu "if programmers were paid to remove code instead of adding it, software would be much better" -- unknown From steve at holdenweb.com Tue Feb 26 00:24:36 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 26 Feb 2008 00:24:36 -0500 Subject: network programming: how does s.accept() work? In-Reply-To: <roy-A89FC2.00124726022008@70-1-84-166.area1.spcsdns.net> References: <6d564fca-3884-4665-8a86-f7e658217a33@e60g2000hsh.googlegroups.com> <446482ef-1fd8-41dc-a8fd-44de8b51a8e8@o10g2000hsf.googlegroups.com> <379fcee4-15e0-48c2-863b-4b7458893cbe@h25g2000hsf.googlegroups.com> <fpuvg9$1l3$1@news.lysator.liu.se> <e4138617-bb4b-4f59-ab78-a49104854d83@60g2000hsy.googlegroups.com> <mailman.1257.1204002544.9267.python-list@python.org> <roy-A89FC2.00124726022008@70-1-84-166.area1.spcsdns.net> Message-ID: <fq07rd$91v$1@ger.gmane.org> Roy Smith wrote: > In article <mailman.1257.1204002544.9267.python-list at python.org>, > Steve Holden <steve at holdenweb.com> wrote: > >> TCP guarantees >> that no two ephemeral port connections from the same client will use the >> same port. > > Where "client" is defined as "IP Address". You could certainly have a > remote machine that has multiple IP addresses using the same remote port > number on different IP addresses for simultaneous connections to the same > local port. Correct. -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From steve at REMOVE-THIS-cybersource.com.au Sun Feb 24 17:50:17 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 24 Feb 2008 22:50:17 -0000 Subject: How about adding rational fraction to Python? References: <b2b884df-b499-4740-9d21-cae87bbd790d@q77g2000hsh.googlegroups.com> <74b95b3b-1d6a-42a6-b55d-e77a868b1ffe@64g2000hsw.googlegroups.com> <K_adnYlVJrhd9SranZ2dnUVZ_iydnZ2d@comcast.com> <dde6d718-fb7d-4bce-a1da-5e78c744cf69@72g2000hsu.googlegroups.com> <naidnRHl24M8GCranZ2dnUVZ_vHinZ2d@comcast.com> <70ecaf16-7308-455f-9048-730b2b2f9f2f@p43g2000hsc.googlegroups.com> <13rf9tvbkt66r2a@corp.supernews.com> <198927a7-9478-42b3-a972-82049f0130ac@u10g2000prn.googlegroups.com> <1bc9bba7-dc7f-4cfe-8e1c-fa5901c9f556@n77g2000hse.googlegroups.com> <97f30679-483d-4751-9a6e-0858b36eb426@d4g2000prg.googlegroups.com> <mailman.1169.1203875215.9267.python-list@python.org> <f4443376-04a0-414e-9eba-149bf9779bef@34g2000hsz.googlegroups.com> <649ac8a9-ae09-4e9b-85c2-f37043af21fd@28g2000hsw.googlegroups.com> <edd61692-2b00-405c-adfe-7f5224097e95@e10g2000prf.googlegroups.com> Message-ID: <13s3t59oejk1mee@corp.supernews.com> On Sun, 24 Feb 2008 11:09:32 -0800, Lie wrote: > I decided to keep the num/den limit low (10) because higher values might > obscure the fact that it do have limits. You do realise that by putting limits on the denominator, you guarantee that the sum of the fractions also has a limit on the denominator? In other words, your "test" is useless. With denominators limited to 1 through 9 inclusive, the sum will have a denominator of 2*3*5*7 = 210. But that limit is a product (literally and figuratively) of your artificial limit on the denominator. Add a fraction with denominator 11, and the sum now has a denominator of 2310; add another fraction n/13 and the sum goes to m/30030; and so on. -- Steven From sajmikins at gmail.com Sun Feb 24 21:14:52 2008 From: sajmikins at gmail.com (Simon Forman) Date: Sun, 24 Feb 2008 18:14:52 -0800 (PST) Subject: How to make "rainbow" RGB values? References: <80b75e15-787a-4369-b7fe-792131143d90@s12g2000prg.googlegroups.com> <mailman.1185.1203901879.9267.python-list@python.org> Message-ID: <bd5b0c82-80e6-4f3c-a059-733e8125bec9@62g2000hsn.googlegroups.com> On Feb 24, 5:09 pm, Andrew McNamara <andr... at object-craft.com.au> wrote: > >I want to map an int to a color on a rainbow spectrum, i.e. for an int > >n in the range 0..N, low values (near 0) should map to the red end, > >and high values (near N) to the blue/violet end. > [...] > >I've tried a simple scheme of overlapping sines, but this resulted in > >too much red and blue, and no indigo/violet. > > Consider using an HSV->RGB conversion function. Saturation (S) and value > (V) should remain constant, while Hue (H) varies to get your rainbow > effect. > > -- > Andrew McNamara, Senior Developer, Object Crafthttp://www.object-craft.com.au/ Hey thank you very much, that worked like a charm! :] There's even a library function in the colorsys module (http:// docs.python.org/lib/module-colorsys.html) Cheers, ~Simon From deets at nospam.web.de Sat Feb 16 05:56:52 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 16 Feb 2008 11:56:52 +0100 Subject: any python wrapper to call .lib static library(ufmod.lib)? In-Reply-To: <d49a5fdc-a089-4fa0-9bf0-acb4d43cb684@i29g2000prf.googlegroups.com> References: <d49a5fdc-a089-4fa0-9bf0-acb4d43cb684@i29g2000prf.googlegroups.com> Message-ID: <61ntrpF20i8ouU2@mid.uni-berlin.de> est schrieb: > I want to play .XM music using Python, now I found ufmod http://ufmod.sourceforge.net > > It only provide a ufmod.lib to be compiled in C/C++/BASIC, and Python > as a scripting language could not handle these static libraries. What > could I do to with these .lib files? I'm not sure if ctypes can use static libraries, but at least you should be able to create a dynamic library from it that you then can use using ctypes. Or you use Pyrex to wrap the static lib. Diez From dotancohen at gmail.com Mon Feb 11 10:49:51 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Mon, 11 Feb 2008 17:49:51 +0200 Subject: OT: Speed of light [was Re: Why not a Python compiler?] In-Reply-To: <000001c86b5e$15a3bfd0$6501a8c0@aristotle> References: <000001c86b5e$15a3bfd0$6501a8c0@aristotle> Message-ID: <880dece00802110749v48fa5275l6422773182ecf22d@mail.gmail.com> On 09/02/2008, Ron Provost <ron.longo at cox.net> wrote: > > The division between philosophy and science can be fine indeed. Philosophy > and science are the two rigorous methods of inquiry into the fundamental > nature of things (other methods include religion and superstition). Because > of it's process, science limits itself to those questions which can be > tested expermientally. Philosophy is left to address the remaining > questions which can be examined through reason (mostly deduction). Of many > of the questions which were thought to be only answerably via philosophy, > often someone finds a way to test some of them. This is very often the case > in areas of philosophy studying the fields involving the mind and nature. > Thus whold chunks of philosophy slowly become the realms of psychology, > lingustics, logic (Which as a whole became the realm of the theoretical > science of math around), and many of the questions about the nature of the > universe, existance and time have become the realm of physics. In this way > philosophy may be thought of as the cutting edge of science. > > Similarly science itself has uncovered new questions which currently can > only be addressed through the methods of philosophy. One of the most > interested and recently practical have been investigations into the > foundations of science. For example, Karl Popper was interested in the > process of science and what constitutes a scientific theory vs. > non-scientific theory. His answer: A scientific theory is falsifyable via > the techniques of science (that is experimentation). This is practical > today, because it excludes the whole "intelligent design" theory from > science, little if any of which is falsifyable. > > Thus the line that divides philosophy and science is fine. The two > disciplies in fact need oneanother. Science uncovers new information used > by philosophy to build new philosophical theories while philosophy spends a > huge amount of time questioning or judging the practices of other fields > such as science in much the same way as the US supreme court is supposed to > work to check on the other branches of the government. +5 Informative Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From steve at REMOVE-THIS-cybersource.com.au Sat Feb 16 22:19:27 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 17 Feb 2008 03:19:27 -0000 Subject: How about adding rational fraction to Python? References: <b2b884df-b499-4740-9d21-cae87bbd790d@q77g2000hsh.googlegroups.com> <61ibo1F1uqso2U1@mid.uni-berlin.de> <188be6e9-bc05-4a72-924b-1de184980002@n58g2000hsf.googlegroups.com> <rOKdnXO5AucGaynanZ2dnUVZ_tDinZ2d@comcast.com> <9b166b3d-89df-4f26-956a-abbd391167e7@i12g2000prf.googlegroups.com> <13rcd3nskgpv91d@corp.supernews.com> <rYWdnY_f89_koSvanZ2dnUVZ_quhnZ2d@comcast.com> <13rde22ktgpu532@corp.supernews.com> <26641b5f-d6cb-45a6-8736-7d130d1a5aee@u10g2000prn.googlegroups.com> <13a4316e-3ce7-4b3e-b418-6efb988a8845@q78g2000hsh.googlegroups.com> <676ca28c-b471-41c8-8661-fcd2ea8c23f0@i12g2000prf.googlegroups.com> <74b95b3b-1d6a-42a6-b55d-e77a868b1ffe@64g2000hsw.googlegroups.com> <K_adnYlVJrhd9SranZ2dnUVZ_iydnZ2d@comcast.com> <dde6d718-fb7d-4bce-a1da-5e78c744cf69@72g2000hsu.googlegroups.com> <naidnRHl24M8GCranZ2dnUVZ_vHinZ2d@comcast.com> <70ecaf16-7308-455f-9048-730b2b2f9f2f@p43g2000hsc.googlegroups.com> Message-ID: <13rf9tvbkt66r2a@corp.supernews.com> On Sat, 16 Feb 2008 18:21:40 -0800, Carl Banks wrote: > Consider what happens when you add two fractions: > > 1/2 + 1/5 > > To do that, you have to take the LCD of the denomintor, in this case 10, > so you get > > 5/10 + 2/10 = 7/10 > > Now imagine that you're adding a lot of different numbers with a lot of > different bases. That LCD's going to be pretty big. It *will* be pretty big, or it *could be* pretty big? The worst case comes from something like this: a/2 + b/3 + c/4 + d/5 + e/6 + ... where the denominator could be as high as n! (for n = the number of fractions you're adding). Since n! gets large quickly, you don't want that. But a less-naive implementation shouldn't be that bad: the lowest common denominator of a/2 + c/4 is 4, not 8. Still, multiplying all the relatively-prime denominators will still get large quickly, just not quite as quickly as n!. Which is where a good fraction implementation should allow you to specify the largest denominator you wish to see. After all, the difference between: 975328755018/6827301285133 and 1/7 is less than 2e-13, or a relative error of approximately 0.0000000001%. If you care about a difference of that magnitude, you're probably already using numpy. An interesting question would be, how large a denominator would you need to beat the precision of floats? My back-of-the-envelope calculation suggests that limiting your denominator to 4503599627370496 is enough to give you a precision as good as floats: # on my PC, the machine accuracy is 2.2204460492503131e-16 # this is the smallest float which, when added to 1.0, # doesn't give 1.0 >>> eps = 2.2204460492503131e-16 >>> 1/eps 4503599627370496.0 The advantage is that while 1000.0+eps gives 1000.0 (which it shouldn't), (1000*4503599627370496 + 1)/4503599627370496 is a perfectly reasonable fraction to work with. Ugly to the human eye perhaps, but if your PC is grinding to a halt on such a fraction, maybe you should take this as a sign that 64K *isn't* enough memory for everybody. *wink* [snip] > The thing I don't like about rationals is that they give a false sense > of security. They are performing reasonably, and then you make a slight > change or some circumstance changes slightly and suddenly they blow up. Or, to put it another way, rationals and floats both are dangerous, but in different ways. The performance of rationals can fall drastically, and floating point calculations can suddenly become inaccurate. You make your choice and take your chances. -- Steven From kay.schluehr at gmx.net Sun Feb 3 00:09:26 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 2 Feb 2008 21:09:26 -0800 (PST) Subject: Python feature request : operator for function composition Message-ID: <b9c459d2-3768-4242-870d-64d0e0ab98ed@v17g2000hsa.googlegroups.com> As you know, there is no operator for function composition in Python. When you have two functions F and G and want to express the composition F o G you have to create a new closure lambda *args, **kwd: F (G (*args, **kwd)) or you write a composition in functional style compose( F, G ) None of these solutions is particular terse. Proposal ------------- I want to propose overloading the logical __and__ operator i.e. '&' for functions s.t. F & G means "compose(F,G)". This suggestion is non- conflicting since & is not used as an operator in combination with function objects yet: given a function object F and an arbitrary object X the combination F & X raises a TypeError when evaluated. Alternatives ----------------- One could use other unused operators like F << G or F * G to write terse function composition expressions. I' m not sure which one is best and would use the proposed & if no one presents arguments against it. From sjmachin at lexicon.net Mon Feb 25 07:20:37 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 25 Feb 2008 04:20:37 -0800 (PST) Subject: Newbie: How can I use a string value for a keyword argument? References: <slrnfs5ad9.vva.morse@ikrg.com> Message-ID: <9acbf4fd-2767-4a29-be5f-21d097125a3e@60g2000hsy.googlegroups.com> On Feb 25, 10:42 pm, Doug Morse <mo... at edoug.org> wrote: > Hi, > > My apologies for troubling for what is probably an easy question... it's just > that can't seem to find an answer to this anywhere (Googling, pydocs, etc.)... > > I have a class method, MyClass.foo(), that takes keyword arguments. For > example, I can say: > > x = MyClass() > x.foo(trials=32) > > Works just fine. > > What I need to be able to do is call foo() with a string value specifying the > keyword (or both the keyword and value would be fine), something along the > lines of: > > x = MyClass() > y = 'trials=32' > x.foo(y) # doesn't work > > or > > x.MyClass() > y = 'trials' > x.foo(y = 32) # does the "wrong" thing > > Surely there's some way to use a string's value as the key for making a method > call with a keyword argument? > > Just for completeness, my goal is simply to read a bunch of key/value pairs > from an INI file (using ConfigObj) and then use those key/value pairs to set a > (3rd party) object's parameters, which must be done with a call along the > lines of "instance.set(key=value)". Obviously, I could create a huge if..elif > statement along the lines of "if y = 'trials': x.foo(trials=32); elif y = > 'speed': x.foo(speed=12);" etc., but then the statement has to be maintained > every time a new parameter is added/changed etc. Plus, such a solution seems > to me grossly inelegant and un-Pythonic. > I'm not quite sure what foo() is really supposed to do ... however the built-in function setattr is your friend. Assuming that ini_dict contains what you have scraped out of your .ini file, you can do: x = MyCLass() for key, value in ini_dict.items(): setattr(x, key, value) You may prefer (I would) to do it inside the class, and maybe do some checking/validation: class MyClass(object): def load(self, adict): for k, v in adict.items(): # do checking here setattr(self, k, v) # much later x = MyClass() x.load(ini_dict) HTH, John From jeff at schwabcenter.com Fri Feb 22 00:23:41 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Thu, 21 Feb 2008 21:23:41 -0800 Subject: Article of interest: Python pros/cons for the enterprise In-Reply-To: <d2777845-6684-4a18-9c8a-e4f58e4e6781@q70g2000hsb.googlegroups.com> References: <e5ae7c80-8bb7-4903-92ff-89e4f62c0239@b29g2000hsa.googlegroups.com><mailman.1019.1203515892.9267.python-list@python.org><2f1527a7-2f66-44c7-9665-4d8ff01fa5ab@28g2000hsw.googlegroups.com><47bd4a24$0$25225$426a74cc@news.free.fr> <f9547b0a-bffa-44b3-8638-12b1dd88fe49@p43g2000hsc.googlegroups.com> <mailman.1057.1203605188.9267.python-list@python.org> <036e93e6-5840-4a3c-8642-67a0a9ec44f2@i7g2000prf.googlegroups.com> <ae0cf9a7-842d-4edf-bd1a-bf4057a694c5@q70g2000hsb.googlegroups.com> <784ec210-f389-4a15-b458-961100de9103@v3g2000hsc.googlegroups.com> <ca9a03a4-ab5e-4e0f-92e4-4982386d7a8e@d5g2000hsc.googlegroups.com> <5MSdncqVGdEXiSPanZ2dnUVZ_vPinZ2d@comcast.com> <d2777845-6684-4a18-9c8a-e4f58e4e6781@q70g2000hsb.googlegroups.com> Message-ID: <AcWdnV4sAZmqwSPanZ2dnUVZ_oSunZ2d@comcast.com> Carl Banks wrote: > On Feb 21, 7:17 pm, Jeff Schwab <j... at schwabcenter.com> wrote: >> Carl Banks wrote: >>> On Feb 21, 1:22 pm, Nicola Musatti <nicola.musa... at gmail.com> wrote: >>>> There are other downsides to garbage collection, as the fact that it >>>> makes it harder to implement the Resource Acquisition Is >>>> Initialization idiom, due to the lack of deterministic destruction. >>> That's not a downside: it's at least a wash. >>> In C++ you manage memory and the language manages resources. In >>> Python you manage resources and the language manages memory. >>> RAII is merely one way of minimizing complexity. Garbage collection >>> is another way. >> If you've already got a generic, language-supported way to manage >> resources (like RAII with deterministic destruction), then why bother >> with garbage collection? > > Because now you have to manage memory? Did you read my post? You > have to manage one thing or the other. Yes, I read your post. You seem to be saying there's some kind of trade-off between automatic management of dynamically allocated memory, and automated management of other kinds of resources. I don't understand why you believe that, so I asked. If you have proper RAII and deterministic destruction, the management is of resources is consistent, and mostly automated. Managing memory is just not that difficult, especially if the vast majority of objects are allocated on the stack or in static memory. A special language feature for managing dynamically allocated memory robs the programmer of a reliable way to clean up resources automatically, without bringing anything of particular value to the table. >> I'm not trying to knock it; it was a big step >> up from C-style "who forgot to delete a pointer" games. It just seems >> to me like a solution to something that's no longer a problem, at least >> in well-written C++ code. I'll take destructors over GC any day. > > About 2% of the objects I creat have resources other than memory. I > would rather manage resources of 2% of objects than manage memory of > 100%. That's not how it works. If I'm going to allocated a C++ object dynamically, I have to assign it to some kind of handle, anyway, so I might as well just use a smart pointer that will delete the object when there are no more references to it. There is no extra effort involved. The most traditional, easiest way to open a file in C++ is to use an fstream object, so the file is guaranteed to be closed when the fstream goes out of scope. CPython offers a similar feature, since you can create a temporary object whose reference count will become zero at the end of the statement where it is defined: $ echo world >hello $ python >>> file('hello').read() 'world\n' It's graceful, easy to write, and a million times better than having to clean up the resource explicitly. A book on Python I was reading recently (either Alex Martelli or Mark Lutz) used this idiom again and again, and every time had to have a footnote about how it wouldn't work right on (e.g.) JPython, because who knows if/when the resource-owning object's finalizer will ever get called. Admittedly, you have to know enough to use the right kinds of objects, but that's something you have to learn anyway. > YMMV, but I suspect mine is the more common opinion, if the > recent (like, 10-year) trend in programming languages is any > indication. I agree that support for non-deterministic GC has grown very popular over the past ten years or so. I don't think that is evidence of it being a good idea though; I suspect that opinion of being the product of widespread ignorance about alternatives to unpredictable GC. From john106henry at hotmail.com Sun Feb 17 12:39:30 2008 From: john106henry at hotmail.com (John Henry) Date: Sun, 17 Feb 2008 09:39:30 -0800 (PST) Subject: pyinstall and matplotlib References: <254161cb-f927-4659-b1a5-c34b5c2953ac@s8g2000prg.googlegroups.com> <3144e444-3542-4550-a280-ff15da8bed0b@l16g2000hsh.googlegroups.com> <rowen-A8050A.10072913022008@news.u.washington.edu> <9d85cb45-2e62-4c4a-9d31-35e5cb9ef3ea@1g2000hsl.googlegroups.com> Message-ID: <f2a09050-c924-4605-bd47-f32715ccfe98@i29g2000prf.googlegroups.com> Anybody willing to help? On Feb 14, 11:17 am, John Henry <john106he... at hotmail.com> wrote: > Thank you for the response. I am having trouble using the script. I > am assuming the TUI is the application this script was developed for > and did my best to replace that with the name of my own. > > To make things simple, let's say we take one of the sample matplotlib > program MULTICOLOR.PY and place that in a directory by itself. I have > attached the modified script below. Notice that I commented out the > "import TUI.Version" and replaced TUI.Version.VersionStr with some > arbitrary number. I have to create a directroy "dest" before running > it. > > When I run this script, there is no error message. Just: > > running install > running build > running install_data > > and then there is an empty directory "MULTICOLOR_2.31_Windows" created > and then nothing else. > > #================================= > from distutils.core import setup > import os > import sys > import matplotlib > import py2exe > > # The following code is necessary for py2exe to find win32com.shell. > # Solution from <http://starship.python.net/crew/theller/moin.cgi/ > WinShell> > > import win32com > import py2exe.mf as modulefinder > > for pth in win32com.__path__[1:]: > modulefinder.AddPackagePath("win32com", pth) > for extra in ["win32com.shell"]: > __import__(extra) > m = sys.modules[extra] > for pth in m.__path__[1:]: > modulefinder.AddPackagePath(extra, pth) > > tuiRoot = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) > roRoot = os.path.join(tuiRoot, "ROPackage") > sys.path = [tuiRoot, roRoot] + sys.path > > #import TUI.Version > > mainProg = os.path.join(tuiRoot, "multicolor.py") > > NDataFilesToPrint = 0 # number of data files to print, per directory > > def addDataFiles(dataFiles, fromDir, toSubDir=None, > inclHiddenDirs=False): > """ > Find data files and format data for the data_files argument of > setup. > > In/Out: > - dataFiles: a list to which is appended zero or more of these > elements: > [subDir, list of paths to resource files] > > Inputs: > - fromDir: path to root directory of existing resource files > - toSubDir: relative path to resources in package; > if omitted then the final dir of fromDir is used > - inclHiddenDirs: if True, the contents of directories whose > names > start with "." are included > > Returns a list of the following elements: > """ > lenFromDir = len(fromDir) > if toSubDir == None: > toSubDir = os.path.split(fromDir)[1] > for (dirPath, dirNames, fileNames) in os.walk(fromDir): > if not inclHiddenDirs: > numNames = len(dirNames) > for ii in range(numNames-1, -1, -1): > if dirNames[ii].startswith("."): > del(dirNames[ii]) > if not dirPath.startswith(fromDir): > raise RuntimeError("Cannot deal with %r files; %s does not > start with %r" %\ > (resBase, dirPath, fromDir)) > toPath = os.path.join(toSubDir, dirPath[lenFromDir+1:]) > filePaths = [os.path.join(dirPath, fileName) for fileName in > fileNames] > dataFiles.append((toPath, filePaths)) > > # Add resources > dataFiles = [] > # TUI resources > for resBase in ("Help", "Scripts", "Sounds"): > toSubDir = os.path.join("MULTICOLOR", resBase) > fromDir = os.path.join(tuiRoot, toSubDir) > addDataFiles(dataFiles, fromDir, toSubDir) > # RO resources > for resBase in ("Bitmaps",): > toSubDir = os.path.join("RO", resBase) > fromDir = os.path.join(roRoot, toSubDir) > addDataFiles(dataFiles, fromDir, toSubDir) > > # Add tcl snack libraries > pythonDir = os.path.dirname(sys.executable) > snackSubDir = "tcl\\snack2.2" > snackDir = os.path.join(pythonDir, snackSubDir) > addDataFiles(dataFiles, snackDir, snackSubDir) > > # Add matplotlib's data files. > matplotlibDataPath = matplotlib.get_data_path() > addDataFiles(dataFiles, matplotlibDataPath, "matplotlibdata") > > if NDataFilesToPrint > 0: > print "\nData files:" > for pathInfo in dataFiles: > print pathInfo[0] > nFiles = len(pathInfo[1]) > for resPath in pathInfo[1][0:NDataFilesToPrint]: > print " ", resPath > if nFiles > NDataFilesToPrint: > print " ...and %d more" % (nFiles - NDataFilesToPrint) > > versDate = "2.31" # TUI.Version.VersionStr > appVers = versDate.split()[0] > distDir = "MULTICOLOR_%s_Windows" % (appVers,) > > inclModules = [ > # "email.Utils", # needed for Python 2.5.0 > ] > # packages to include recursively > inclPackages = [ > "MULTICOLOR", > "RO", > "matplotlib", > "dateutil", # required by matplotlib > "pytz", # required by matplotlib > # "matplotlib.backends", > # "matplotlib.numerix", > # "encodings", > # "numpy", > # "email", # needed for Python 2.5 > ] > > setup( > options = dict( > py2exe = dict ( > dll_excludes = [ > # the following are for matplotlib 0.87: > "libgdk_pixbuf-2.0-0.dll", > "libgobject-2.0-0.dll", > "libgdk-win32-2.0-0.dll", > "wxmsw26uh_vc.dll", > ], > excludes = [ # modules to exclude > "_gtkagg", > "_wxagg", > ], > #includes = inclModules, > packages = inclPackages, > ) > ), > windows=[ # windows= for no console, console= for console > dict( > script = mainProg, > dest_base = "MULTICOLOR", > icon_resources = [(1, "python.ico")], > ), > ], > data_files = dataFiles, > ) > > # rename dist to final directory name > os.rename("dist", distDir) > > On Feb 13, 10:07 am, "Russell E. Owen" <ro... at cesmail.net> wrote: > > > In article > > <3144e444-3542-4550-a280-ff15da8be... at l16g2000hsh.googlegroups.com>, > > John Henry <john106he... at hotmail.com> wrote: > > > > On Feb 9, 2:53 pm, John Henry <john106he... at hotmail.com> wrote: > > > > Has anybody been able to create an exe of their python applications > > > > involving matplotlib using pyinstall (ver 1.3)? I am getting a: > > > > > RuntimeError: Could not find the matplotlib data files > > > > > when I attempt to run the exe created. > > > > > In searching the web, it appears this is an issue when others tried to > > > > use py2exe as well. Unfortunately, the few hits I saw doesn't include > > > > enough details to inspire me as to what I should be doing in my > > > > pyinstall .spec file. > > > > > Does anybody has an example or information about this? > > > > > Thanks, > > > > Well, looks like nobody has an answer to this question. > > > > How'bout py2exe or other ways of creating exe files out of matplotlib > > > projects? Has anybody been able to do that? (I am cross-posting > > > these messages to the matploblib mailing list). > > > For py2exe I have appended a setup script I use to bundle an application > > that includes matplotlib. I am no Windows expert and there are probably > > better ways to do it, but it does work. I have made no attempt to strip > > out extra stuff. > > > (As for pyinstaller:a year or so ago I tried to use it to make a bundled > > *unix* version of my app. If that had worked I'd have considered trying > > to use it for Windows as well. But after a lot of experimenting I was > > never able to get anything even close to functional. Maybe it's better > > now.) > > > -- Russell > > > from distutils.core import setup > > import os > > import sys > > import matplotlib > > import py2exe > > > # The following code is necessary for py2exe to find win32com.shell. > > # Solution from > > <http://starship.python.net/crew/theller/moin.cgi/WinShell> > > import win32com > > import py2exe.mf as modulefinder > > for pth in win32com.__path__[1:]: > > modulefinder.AddPackagePath("win32com", pth) > > for extra in ["win32com.shell"]: > > __import__(extra) > > m = sys.modules[extra] > > for pth in m.__path__[1:]: > > modulefinder.AddPackagePath(extra, pth) > > > tuiRoot = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) > > roRoot = os.path.join(tuiRoot, "ROPackage") > > sys.path = [tuiRoot, roRoot] + sys.path > > import TUI.Version > > mainProg = os.path.join(tuiRoot, "runtui.py") > > > NDataFilesToPrint = 0 # number of data files to print, per directory > > > def addDataFiles(dataFiles, fromDir, toSubDir=None, > > inclHiddenDirs=False): > > """Find data files and format data for the data_files argument of > > setup. > > > In/Out: > > - dataFiles: a list to which is appended zero or more of these > > elements: > > [subDir, list of paths to resource files] > > > Inputs: > > - fromDir: path to root directory of existing resource files > > - toSubDir: relative path to resources in package; > > if omitted then the final dir of fromDir is used > > - inclHiddenDirs: if True, the contents of directories whose names > > start with "." are included > > > Returns a list of the following elements: > > """ > > lenFromDir = len(fromDir) > > if toSubDir == None: > > toSubDir = os.path.split(fromDir)[1] > > for (dirPath, dirNames, fileNames) in os.walk(fromDir): > > if not inclHiddenDirs: > > numNames = len(dirNames) > > for ii in range(numNames-1, -1, -1): > > if dirNames[ii].startswith("."): > > del(dirNames[ii]) > > if not dirPath.startswith(fromDir): > > raise RuntimeError("Cannot deal with %r files; %s does not > > start with %r" %\ > > (resBase, dirPath, fromDir)) > > toPath = os.path.join(toSubDir, dirPath[lenFromDir+1:]) > > filePaths = [os.path.join(dirPath, fileName) for fileName in > > fileNames] > > dataFiles.append((toPath, filePaths)) > > > # Add resources > > dataFiles = [] > > # TUI resources > > for resBase in ("Help", "Scripts", "Sounds"): > > toSubDir = os.path.join("TUI", resBase) > > fromDir = os.path.join(tuiRoot, toSubDir) > > addDataFiles(dataFiles, fromDir, toSubDir) > > # RO resources > > for resBase in ("Bitmaps",): > > toSubDir = os.path.join("RO", resBase) > > fromDir = os.path.join(roRoot, toSubDir) > > addDataFiles(dataFiles, fromDir, toSubDir) > > > # Add tcl snack libraries > > pythonDir = os.path.dirname(sys.executable) > > snackSubDir = "tcl\\snack2.2" > > snackDir = os.path.join(pythonDir, > > ... > > read more ? From steve at holdenweb.com Wed Feb 6 21:36:37 2008 From: steve at holdenweb.com (Steve Holden) Date: Wed, 06 Feb 2008 21:36:37 -0500 Subject: python beginner problem(?) In-Reply-To: <47AA4AC1.6080404@holdenweb.com> References: <13qkgb8iub6bv2d@news.supernews.com> <47AA4AC1.6080404@holdenweb.com> Message-ID: <fodqrl$22s$2@ger.gmane.org> Steve Holden wrote: > Alan Illeman wrote: >> Win2k Pro - installed python: ok >> [...] >> ================================================= >>>>> C:\Python25\Lib\site-packages\pythonwin\pywin\mfc\object.py: >> 23: DeprecationWarning: raising a string exception is deprecated >> raise win32ui.error, "The MFC object has died." >> pwd=secret;database=master;uid=sa;server=mpilgrim >> ================================================= >> >> DiveIntoPython example 2.1 result: >> server=mpilgrim;uid=sa;database=master;pwd=secret >> >> ..which I realise is essentially the same (except for order). >> >> I haven't ever (not that I remember) installed MFC. >> >> Help! >> [...] > I am hugely surprised to find that PythonWin apparently raises string > exceptions: this is an old programming technique, which should have been > removed from anything designed to run on Python 2.5. That is why you see > the message: it's only a warning, so you can ignore it. I am copying > Mark on this message in case he's unaware of the issue. [...] In a private reply Mark Hammond says he will fix this in the next release - thanks for the report! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From castironpi at gmail.com Mon Feb 18 21:52:22 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 18 Feb 2008 18:52:22 -0800 (PST) Subject: Passing a callable object to Thread References: <52465ed8-7d25-40ca-be69-478b308af879@u10g2000prn.googlegroups.com> <7xir0psq9l.fsf@ruckus.brouhaha.com> <452d63ea-3373-4393-9c28-38116f96d2e9@u10g2000prn.googlegroups.com> <mailman.843.1203131001.9267.python-list@python.org> <7xzlu1bmdj.fsf@ruckus.brouhaha.com> <mailman.846.1203134004.9267.python-list@python.org> <h6SdnbMFFusl8ivanZ2dnUVZ_jCdnZ2d@comcast.com> <7x3artbhwl.fsf@ruckus.brouhaha.com> <zO-dnfnEyInh6SvanZ2dnUVZ_i2dnZ2d@comcast.com> <c0c703ae-b1f6-434d-b37c-edcbca3a03e7@s8g2000prg.googlegroups.com> <luidnTNq6NxxmCfanZ2dnUVZ_jOdnZ2d@comcast.com> <ad3a39bb-5f93-4025-97c7-419b89ce0fb6@d4g2000prg.googlegroups.com> <V4qdnctmqr7LjifanZ2dnUVZ_hadnZ2d@comcast.com> Message-ID: <23415b21-29ec-4345-a295-3c3bdfe8d0ba@s8g2000prg.googlegroups.com> On Feb 18, 5:23?pm, Jeff Schwab <j... at schwabcenter.com> wrote: > castiro... at gmail.com wrote: > > On Feb 18, 4:26 pm, Jeff Schwab <j... at schwabcenter.com> wrote: > >> Lie wrote: > >>> On Feb 16, 12:29 pm, Jeff Schwab <j... at schwabcenter.com> wrote: > >>>> Paul Rubin wrote: > >>>>> Jeff Schwab <j... at schwabcenter.com> writes: > >>>>>> Why not? ?They seem intuitive to me. ?I would find it weird if you > >>>>>> couldn't have 0-tuple, and even weirder if you couldn't have a > >>>>>> 1-tuple. ? Maybe my brain has been warped by too much C++ code. > >>>>> The idea is that a 2-tuple (of numbers, say) is a pair of numbers, a > >>>>> 3-tuple is three numbers, and a 1-tuple is one number. ?That would > >>>>> mean a number and a 1-tuple of numbers are the same thing, not > >>>>> separate types. > >>>> No, that doesn't follow. ?A set with one element is not the same thing > >>>> as that element, a sequence of one element is not the same thing as that > >>>> element, and a tuple with one element is not the same thing as that element. > >>> Probably the analogue of tuples in human language would be like this: > >>> A: What ice-cream flavour do you have? > >>> B: "Vanilla", "Chocolate", and "Strawberry" > >>> If, for example, he only have Vanilla: > >>> A: What ice-cream flavour do you have? > >>> B: "Vanilla" > >>> This way of thinking makes 1-tuple the same as the element itself. > >> Yes. ?I first heard the term "tuple" in a physics class, where it was > >> used to mean that a mathematical function took an arbitrary number of > >> objects. ?It was by analog with "triple, quadruple, quintuple... > >> n-tuple." ?That's a different context than computer science, though, > >> which is a specific branch of mathematics with its own terminology. ?In > >> CS, a tuple is a kind of data structure that is specifically not > >> identical with any of its elements. ?That's the sort of tuple used in > >> Python.- Hide quoted text - > > >>>> a= object() > >>>> (a,) is a > > False > > (a,) is not identical with a. > > >>>> (a,) is (a,) > > False > > The tuple on the left is not identical with the tuple on the right, even > though they are equivalent. > > >>>> a is a > > True > > The variable on the left is identical with the one on the right. ?This > is not the same comparison as "(a,) is (a,)", which actually contains > the construction of two distinct objects. ?The moral equivalent of "a is > a" would be: > > ?>>> b = (a,) > ?>>> b is b > True > > An interesting thing about Python is that numbers of built-in types are > flyweights. ?Unlike literals of non-flyweight types, distinct instances > of a given numeric literal actually refer to the same object: > > ?>>> 5 is 5 > True > ?>>> 999999999999999999999999999999 is 999999999999999999999999999999 > True > ?>>> 3.5 is 3.5 > True > > I wonder, will this be true of the upcoming Fraction class? > > >>>> (a,) == (a,) > > True > > The two tuples are equivalent (though not identical). > > >>>> a= [] > >>>> a.append( a ) > >>>> a > > [[...]] > > That's cool. ?I don't think would have known off the top of my head how > the interactive interpreter would display something like that. ?Talk > about a cyclic reference... > > >>>> tuple(a) is tuple(a) > > False > > The tuple on the left is not identical with the tuple on the right, even > though they are equivalent. ?This is the sample as one of your earlier > examples, just with slightly different syntax. > > > hasVanilla= True > > hasStrawberry= True > > hasChocolate= True > > if hasVanilla: > > ? print "Vanilla" > > if hasVanilla and not hasChocolate: > > ? print "and" > > if hasStrawberry: > > ? print "Strawberry" > > if hasVanilla or hasStrawberry and hasChocolate: > > ? print "and" > > if hasChocolate: > > ? print "Chocolate." > > You've tried to implement a set using a set of flags to indicate whether > various items have membership in that set. ?See how an object > representing a given flavor would have to be distinct from the object > (boolean flag) indicating its set membership? ?Btw, your formatting > could use some work. :) ?Some flavor combinations cause extra "ands" to > be printed. Here's a little test harness, with PEP-friendly variable > names, and showing how your booleans corresponding directly with > traditional bit-bucket flag sets: > > def print_flavors(flags): > > ? ? ?print flags > > ? ? ?vanilla = flags & 1 > ? ? ?strawberry = flags & 2 > ? ? ?chocolate = flags & 4 > > ? ? ?if vanilla: > ? ? ? ? ?print "Vanilla" > ? ? ?if vanilla and not chocolate: > ? ? ? ? ?print "and" > ? ? ?if strawberry: > ? ? ? ? ?print "Strawberry" > ? ? ?if vanilla or strawberry and chocolate: > ? ? ? ? ?print "and" > ? ? ?if chocolate: > ? ? ? ? ?print "Chocolate." > > if __name__ == '__main__': > ? ? ?for flavor_flags in range(8): > ? ? ? ? ?print_flavors(flavor_flags)- Hide quoted text - > > - Show quoted text - a= set( 'Vanilla', 'Chocolate', 'Strawberry' ) flavors= [ Flavors( i ) for i in a ] b= list( a ) if len( b )> 1: b[-1]= "and "+ b[-1] return ", ".join( b ) string.join() works on sets, but the 'and', appears only before the last element if there is more than one. Why not "if b> 1", since len( integer ) always fails? Could also use b= ", ".join( a ) try: return b[ :b.rfind( ',' ) ]+ ' and'+ b[ b.rfind( ',' ): ] except IndexError: return b But -NOT-: flavors= set( Flavors( 'Vanilla' ), Flavors( 'Chocolate' ), Flavors( 'Strawberry' ) ) ... since set( Flavors( 'Vanilla' ), Flavors( 'Vanilla' ) ) has size two. However: flavors= set( Flavors.Get( 'Vanilla' ), Flavors.Get( 'Chocolate' ), Flavors.Get( 'Strawberry' ) ) is a possibility: class Flavors: @classmethod def Get( cls, flavor ): return cls.flavors.setdefault( flavor, cls( flavor ) ) def __init__( self, flavor ): self.flavor= flavor flavors= {} , since __init__ cannot return other objects, but classmethods can, just like C++. Fm. Pres. G.H.W. Bush endorses Sen. McCain. Who is Bush "41"? From arnodel at googlemail.com Fri Feb 8 11:06:22 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 8 Feb 2008 08:06:22 -0800 (PST) Subject: How to identify which numbers in a list are within each others' range References: <6b4ac79b-6267-438d-8b28-aa4bba78a586@i3g2000hsf.googlegroups.com> <1ffed8a2-f00b-4913-802f-b2cc9fa0ab19@i12g2000prf.googlegroups.com> <47ac5dfa$1_1@news.bluewin.ch> Message-ID: <03b65c15-857b-4f93-9718-13e8e2b61e12@m34g2000hsf.googlegroups.com> On Feb 8, 1:48?pm, Boris Borcic <bbor... at gmail.com> wrote: > Arnaud Delobelle wrote: > > (...) > > > > > from itertools import chain > > > def overlaps(lst): > > ? ? bounds = chain(*(((x[1],i), (x[2], i)) for i,x in enumerate(lst))) > > imho, this is a uselessly painful equivalent of > > ? ? ? ?bounds = ((x[k],i) for i,x in enumerate(lst) for k in (1,2)) > > Cheers, BB I did mention that it was awkward (but at the time I just wrote what came to mind) - thank you for providing a much improved version. It doesn't deter from the fact that the algorithm is of optimal complexity (modulo sorting of the list). -- Arnaud From j.foster.davis at gmail.com Sat Feb 23 16:12:12 2008 From: j.foster.davis at gmail.com (Jacob Davis) Date: Sat, 23 Feb 2008 13:12:12 -0800 Subject: graphing/plotting with python and interface builder In-Reply-To: <62ams7F2165caU1@mid.uni-berlin.de> References: <mailman.1124.1203739744.9267.python-list@python.org> <62ams7F2165caU1@mid.uni-berlin.de> Message-ID: <72720FAB-163F-469E-9ED5-845F557CB56D@gmail.com> I found SM2DGraphView, but I guess that I am too much of a newbie with interface builder and pyobjc to figure out how to get SM2DGraphView to work. Are there any good tutorials (or better yet, examples) of how to get SM2DGraphView to work? I don't know pyobjc well at all. Thanks Jake On Feb 23, 2008, at 5:54 AM, Diez B. Roggisch wrote: > Jacob Davis schrieb: >> Hi. >> >> I am developing for mac and using Xcode and Interface Builder 3.0. I >> can make a simple application, but I am having a hard time trying to >> figure out a good way to create a graph or plot for a class project. >> >> Does anybody have any tips on where to get started, or on how to do >> this? >> >> I have searched far for several days now, but I don't know if I am on >> the right track. Any help is much appreciated. > > I use > > http://developer.snowmintcs.com/frameworks/sm2dgraphview/index.html > > > under 10.4. I don't see why it shouldn't work under 10.5. I assume you > use pyobjc? I had to use the signature-decorator to make the > SM2DGraphDataSource-category work - but I'm not sure if pyobjc 2.0 > changes anything in that respect. > > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list From steve at REMOVE-THIS-cybersource.com.au Wed Feb 27 21:32:19 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 28 Feb 2008 02:32:19 -0000 Subject: How about adding rational fraction to Python? References: <b2b884df-b499-4740-9d21-cae87bbd790d@q77g2000hsh.googlegroups.com> <7xk5kra0p1.fsf@ruckus.brouhaha.com> <fq1ved$6ta$1@rumours.uwaterloo.ca> <7xy797s966.fsf@ruckus.brouhaha.com> <fq224h$7uh$1@rumours.uwaterloo.ca> <b135e0e7-38fd-44f9-a67b-00b69af5ecc6@34g2000hsz.googlegroups.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> Message-ID: <13sc79jk28hfrf1@corp.supernews.com> On Wed, 27 Feb 2008 17:07:37 -0800, Paul Rubin wrote: > Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> writes: >> Oh come on. With a function named "mean" that calculates the sum of a >> list of numbers and then divides by the number of items, what else >> could it be? > > You have a bunch of marbles you want to put into bins. The division > tells you how many marbles to put into each bin. That would be an > integer since you cannot cut up individual marbles. (Actually you can. As a small child, one of my most precious possessions was a marble which had cracked into two halves.) No, that doesn't follow, because you don't get the result you want if the number of marbles is entered as Decimals or floats. Maybe the data came from a marble-counting device that always returns floats. You're expecting the function to magically know what you want to do with the result and return the right kind of answer, which is the wrong way to go about it. For example, there are situations where your data is given in integers, but the number you want is a float. # number of 20kg bags of flour per order >>> data = [5, 7, 20, 2, 7, 6, 1, 37, 3] >>> weights = [20*n for n in data] >>> mean(weights) 195.55555555555554 If I was using a library that arbitrarily decided to round the mean weight per order to 195kg, I'd report that as a bug. Maybe I want the next highest integer, not lowest. Maybe I do care about that extra 5/9th of a kilo. It simply isn't acceptable for the function to try to guess what I'm going to do with the result. >> You can always imagine corner cases where some programmer, somewhere, >> has some bizarre need for a mean() function that truncates when given a >> list of integers but not when given a list of floats. Making that the >> default makes life easy for the 0.1% corner cases and life harder for >> the 99.9% of regular cases, which is far from the Python philosophy. > > I think it's more important that a program never give a wrong answer, > than save a few keystrokes. So, that polymorphic mean function is a bit > scary. It might be best to throw an error if the args are all integers. > There is no definitely correct way to handle it so it's better to > require explicit directions. Of course there's a correct way to handle it. You write a function that returns the mathematical mean. And then, if you need special processing of that mean, (say) truncating if the numbers are all ints, or on Tuesdays, you do so afterwards: x = mean(data) if all(isinstance(n, int) for n in data) or today() == Tuesday: x = int(x) I suppose that if your application is always going to truncate the mean you might be justified in writing an optimized function that does that. But don't call it "truncated_mean", because that has a specific meaning to statisticians that is not the same as what you're talking about. Paul, I'm pretty sure you've publicly defended duck typing before. Now you're all scared of some imagined type non-safety that results from numeric coercions. I can't imagine why you think that this should be allowed: class Float(float): pass x = Float(1.0) mean([x, 2.0, 3.0, 5.0]) but this gives you the heebie-geebies: mean([1, 2.0, 3.0, 5.0]) As a general principle, I'd agree that arbitrarily coercing any old type into any other type is a bad idea. But in the specific case of numeric coercions, 99% of the time the Right Way is to treat all numbers identically, and then restrict the result if you want a restricted result, so the language should make that the easy case, and leave the 1% to the developer to write special code: def pmean(data): # Paul Rubin's mean """Returns the arithmetic mean of data, unless data is all ints, in which case returns the mean rounded to the nearest integer less than the arithmetic mean.""" s = sum(data) if isinstance(s, int): return s//len(data) else: return s/len(data) -- Steven From bearophileHUGS at lycos.com Thu Feb 28 09:40:17 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 28 Feb 2008 06:40:17 -0800 (PST) Subject: Indentation and optional delimiters References: <555b548f-1296-4374-b6ce-65691d1dbb7f@s8g2000prg.googlegroups.com> <13s92u3sibaus4f@corp.supernews.com> <3f55d3b1-c32c-42bc-bd4b-52e2725049b0@v3g2000hsc.googlegroups.com> <13scm5m9jmdns02@corp.supernews.com> Message-ID: <318b03dc-4cc5-49de-aeb9-e1b6e590007f@u10g2000prn.googlegroups.com> Steven D'Aprano: >the readability of your posts will increase a LOT if you break it up into paragraphs,< You are right, I'll try to do it (when I go in flux state I write quickly, but I tend to produce long paragraphs). >The thing is, make-another-copy and make-another-reference are semantically different things: they mean something different. Expecting the compiler to tell whether I want "x = y" to make a copy or to make another reference is never going to work,< But the default behavior may become the "true" copy, that seems simpler for a newbie to grasp. The language then may give a tool to use references too (like passing arrays to functions in Pascal, you can use "var" for pass-by-reference reference). >It specifically talks about C, but it's relevant to Python, and all hypothetical future languages. Think about string concatenation in Python.< It's a nice article, and it says many things. (The D language manages strings in a good enough way, they are represented below the hood as stack allocated structs of [pointer_begin, length] in UTF8/16/32 (C strings are available too, static arrays of chars too, etc) that point to a block on the GC-ected heap. Such representation may change into a [pointer_begin, pointer_end] in the future, to speed up iterations. But it lacks still a good way to do a reserve() like in STL C++ Vector, that requires a third value in the struct). I presume you have linked me that article because it essentially explains the concept of "leaking abstractions", that is even if your system allows you to manage it through high-level abstractions, you often have to know what's under the cover anyway, because the behavior of such subsystems may have a large impact on the performance of the high-level operations you try to perform. If this is why you have pointed me that article, then I have the following comments: 1) That's why when I have started learning Python I was asking here about the computational complexity of various operations done by Python, like the string methods. Later I have found that the best strategy is to just perform thousands of little benchmarks. Even later I have started to just read the C sources of Python :-) 2) The language I was talking about isn't meant to replace C or Java, it's meant for newbies, students, and to be used on small problems. If the problem is small enough, you can survive even if you ignore the subsystems of the system you are using. So if you have 10 small strings that you want to join once in a Python program you can use the "+" too, without wasting too much running time. If you want more speed or you want to solve bigger problems you can use different languages. 3) Subsystems may have a different degree of subsystem insulation: 3a) One subsystem that exists when I run a Python program is its GC, but in most situations I can just ignore it, it works in a transparent way, the abstraction doesn't leak much. Only in rare situations I may have to disable it during a very fast creation of a complex data structure, so it doesn't slow down that too much. When I do even more complex things, with complex classes that use __del__ I may have to think about the GC even more, but in most small programs the Python GC is transparent. 3b) On the other hand, when I use the D language in a simple way I can ignore its GC, using D almost as Java. But often I have to use D at a lower level (because otherwise I prefer to use Python), I have to manually allocate and deallocate data from the C heap or from the GC heap, and in such cases the situation becomes hairy quickly, because I don't know how exactly the GC will interact with my manual memory management (that Python disallows). So often in D the GC is an almost mysterious subsystem, and a very leaking abstraction (if you do complex windows programming in C++, with smart pointers, etc, you may have similar problems, so it's not a problem limited to D). >They're different from the numbers you can't express exactly in base 2 numbers, and different from the numbers you can't express exactly as rationals, but they're there, waiting to trip you up:< If you want to become a CS student, a programmer, you have to know something about IEEE 754, or even you have to study "What Every Computer Scientist Should Know About Floating-Point Arithmetic". But for a person that doesn't want to spend so much time to solve a small and not important problem, and doesn't want to hire a programmer to solve that problem do that for him/her, a very high level language may offer ways to the same mathematical operations without too much problems. If you use an old HP 48 calculator you have to be careful, but often it gives you good answers :-) Thank you, bearophile From tnleeuw at gmail.com Thu Feb 21 08:20:08 2008 From: tnleeuw at gmail.com (Tim van der Leeuw) Date: Thu, 21 Feb 2008 14:20:08 +0100 Subject: Sending key-presses to other programs on Windows, and settings of controls? Message-ID: <c1f38650802210520u1168628ew35dc1f079d4b0633@mail.gmail.com> Hi, I'm looking for ways to send keypresses to another application on Windows XP, and to set values of Windows Controls (all of them text-boxes). This is to try automate testing of the application. I think I've done things like that before from Python, but I don't remember for sure. Can this be done? Using the Win32-all extensions perhaps? Or perhaps with the CTypes module? Any pointers are appreciated! Kind regards, --Tim van der Leeuw -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080221/e4563deb/attachment.html> From nejtak... Sun Feb 3 12:50:42 2008 From: nejtak... (Troels Thomsen) Date: Sun, 3 Feb 2008 18:50:42 +0100 Subject: Does anyone else use this little idiom? In-Reply-To: <3d809532-08e1-4939-a893-ed3808fa44c4@i12g2000prf.googlegroups.com> References: <e82b13fe-0974-400f-ac5b-0583a86fd9e0@q39g2000hsf.googlegroups.com> <3d809532-08e1-4939-a893-ed3808fa44c4@i12g2000prf.googlegroups.com> Message-ID: <47a5ff21$0$15879$edfadb0f@dtext01.news.tele.dk> >for action in repeat(f, n): action() >I don't know how 'Pythonic' this would be... agree, or this: import itertools def f1(): print "hello" [f() for f in itertools.repeat(f1,6)] tpt From http Thu Feb 14 03:50:35 2008 From: http (Paul Rubin) Date: 14 Feb 2008 00:50:35 -0800 Subject: ANN: NUCULAR B3 Full text indexing (now on Win32 too) References: <8e155507-f487-40d6-96e3-7aaa8f431fcd@e23g2000prf.googlegroups.com> <7xir0smw44.fsf@ruckus.brouhaha.com> <fp0saf$lt0$1@atlantis.news.tpi.pl> <7xir0sq87q.fsf@ruckus.brouhaha.com> <fp0ucf$p6j$1@nemesis.news.tpi.pl> Message-ID: <7xabm353c4.fsf@ruckus.brouhaha.com> Jarek Zgoda <jzgoda at o2.usun.pl> writes: > > I don't know what Sphinx is. > http://www.sphinxsearch.com/ Thanks, looks interesting, maybe not so good for what I'm doing, but worth looking into. There is also Xapian which again I haven't looked at much, but which has fancier PIR (probabilistic information retrieval) capabilities than Lucene or the version of Nucular that I looked at. The main thing killing most of the search apps that I'm involved with is disk latency. If Aaron is listening, I might suggest offering a config option to redundantly recording the stored search fields with every search term in the index. That will bloat the indexes by a nontrivial constant factor (maybe 5x-10x) but even terabyte disks are dirt cheap these days, so you still index a lot of data, and present large result sets without having to do a disk seek for every result in the set. I've been meaning to crunch some numbers to see if this actually makes sense. Unfortunately, the concept of the large add-on memory card seems to have vanished. It would be very useful to have a cheap x86 box with a buttload of ram (say 64gb), using commodity desktop memory and extra modules for ECC. It would be ok if it went over some slow interface so that it was 10x slower than regular ram. That's still 100x faster than a flash disk and 1000x faster than a hard disk. From http Thu Feb 14 02:59:37 2008 From: http (Paul Rubin) Date: 13 Feb 2008 23:59:37 -0800 Subject: ANN: NUCULAR B3 Full text indexing (now on Win32 too) References: <8e155507-f487-40d6-96e3-7aaa8f431fcd@e23g2000prf.googlegroups.com> <7xir0smw44.fsf@ruckus.brouhaha.com> <fp0saf$lt0$1@atlantis.news.tpi.pl> Message-ID: <7xir0sq87q.fsf@ruckus.brouhaha.com> Jarek Zgoda <jzgoda at o2.usun.pl> writes: > Did you (or anyone else) compare Nucular with Solr and Sphinx > feature-by-feature? Nucular when I looked at it was in an early alpha release and looked interesting and promising, but was nowhere near as built-out as Solr. It may be closer now; I haven't yet had a chance to look at the new release. I don't know what Sphinx is. From gagsl-py2 at yahoo.com.ar Thu Feb 7 21:48:53 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 08 Feb 2008 00:48:53 -0200 Subject: embedded python in c++ packaging References: <3a4a8f930802070839n31ac4d88t96d64a4138d23ff4@mail.gmail.com> <fofi2h$ags$1@ger.gmane.org> <op.t56bq7tex6zn5v@gabriel2.softlabbsas.com.ar> <3a4a8f930802071505x70946723wabe84ad9ea4ae465@mail.gmail.com> Message-ID: <op.t56p3rqgx6zn5v@gabriel2.softlabbsas.com.ar> En Thu, 07 Feb 2008 21:05:46 -0200, Furkan Kuru <furkankuru at gmail.com> escribi?: > I do not have access to my development machine right now. > but is it enough adding just a simple line at the top of my main python > file > 'sys.path.append("modules.zip")' before importing any other modules? Almost. Some imports (site, warnings, os...) are done when Py_Initialize is executed, before there is a chance of modifying sys.path. You'll have to modify the environment (PYTHONPATH var) or look at how py2exe does that. Or use the name pythonXX.zip, which is already in sys.path (see PEP 273 http://www.python.org/dev/peps/pep-0273/ ) -- Gabriel Genellina From Matthew_WARREN at bnpparibas.com Fri Feb 1 10:11:02 2008 From: Matthew_WARREN at bnpparibas.com (Matthew_WARREN at bnpparibas.com) Date: Fri, 1 Feb 2008 15:11:02 +0000 Subject: very simple Genetic Algorithm completed In-Reply-To: <674f29dc-7374-4125-9a5f-adc2bfbce16f@k39g2000hsf.googlegroups.com> Message-ID: <OFBFF0921E.68E0A221-ON802573E2.004F34CA-802573E2.00536868@bnpparibas.com> On Jan 31, 10:43?am, Matthew_WAR... at bnpparibas.com wrote: > > Hi, > > > > I got some help with this from here, and there's been a little bit of > > discussion around GA's recently, so thought I'd post up my likey slow and > > clunky version of a GA that in essence just 'evolves' a solution to 'make a > > Some improvement tips: > > 0. Tack this bit onto the end of quickga.py, and you wont have to > write a separate routine to import quickga and invoke evolve(): > > if __name__ == "__main__": > evolve() I hear you, but something I dont tend to do as I use pythons interactive prompt a lot, and I like things not autorunning when I import them. I normally add it in at the end of writing something. > 1. Remove all calls to floatify, and instead start your program with: > from __future__ import division > On my system this gained about 16% improvement. > I was sure there must be a nicer way of achieving that, thanks :) > > 2. Bugfix: In 2 places, change: > newgene=genes[randint(0,14)-1] > to > newgene=genes[randint(0,14-1)] > > randint(a,b) returns values from a to b inclusive, and genes is a list > containing 14 elements (so you want subscripts from 0 to 13). (Usingd > subscripts from -1 to 13 will bias the selection of genes to use twice > as many of the last item in the list, since both -1 and 13 will give > that value.) > > Similarly, change: > > s=rationalise_signs(''.join([ genes[randint(0,len(genes))-1] ... > to: > s=rationalise_signs(''.join([ genes[randint(0,len(genes)-1)] ... > Doh! - I was assuming I would get 1-14, not 0-14 with randint. Brain slip. > > 3. Change mutate to build a list instead of a string. Then use > ''.join() at the end to convert the list into a single string return > value. > Interesting. I knew string operations arent necesarilly the quickest but I didnt think of lists as being any quicker because I'm sure I've read somewhere pythons strings are treated like lists, and I assumed the ''.join() would undo any savings. I'll go read up on it :) > > > (This was less of a speed improvement than I thought it would be, but > IIRC, the optimization of successive string concatentions is only > available when running Python on Windows. If you are running on Linux, > this should have more benefit.) It is windows. > > > 4. Include psyco to cut execution time in half. Put this at the top I was doing this as your mail arrived :) > > > 5. On a hunch that many of your individuals are the same string, I > lifted the call to eval out of express() into a separate routine > called evaluate(), and added a memoizing cache to skip the call to > eval if the string had been eval'ed before - if so, the value is > reported from the cache. This chopped another 40% off the runtime. > > evalcache = {} > def evaluate(s): > if s in evalcache: > ret = evalcache[s] > else: > ret = eval(s) > evalcache[s] = ret > return ret > > (A note on timing this code: since there are many calls to > randomization methods, consistent timing requires an explicit call to > random.seed() to ensure that a consistent set of random numbers is > used. Otherwise, the timing gets thrown off by the randomization, > which sends the program down different paths.) Thats great! not something I would have thought of, caching the eval results. Simple and effective :) > > > 6. This is another change that had little effect, but I'll at least > put it out there (a leftover from an algorithmic optimization course I > took ages ago). Instead of: > > fitness=abs(fitvalue-expression) > > try using: > > fitness=(fitvalue-expression)*(fitvalue-expression) > I originally had this. I was seeing absoloutley huuge int's appear and wondered if dealing with those in memory might slow things down. I'll try it either way. ..timing the code. I was just puzzling over that, and yep a call to seed() will fix it. Thanks for the suggestions and hints, esp the cache idea. Matt. This message and any attachments (the "message") is intended solely for the addressees and is confidential. If you receive this message in error, please delete it and immediately notify the sender. Any use not in accord with its purpose, any dissemination or disclosure, either whole or partial, is prohibited except formal approval. The internet can not guarantee the integrity of this message. BNP PARIBAS (and its subsidiaries) shall (will) not therefore be liable for the message if modified. Do not print this message unless it is necessary, consider the environment. --------------------------------------------- Ce message et toutes les pieces jointes (ci-apres le "message") sont etablis a l'intention exclusive de ses destinataires et sont confidentiels. Si vous recevez ce message par erreur, merci de le detruire et d'en avertir immediatement l'expediteur. Toute utilisation de ce message non conforme a sa destination, toute diffusion ou toute publication, totale ou partielle, est interdite, sauf autorisation expresse. L'internet ne permettant pas d'assurer l'integrite de ce message, BNP PARIBAS (et ses filiales) decline(nt) toute responsabilite au titre de ce message, dans l'hypothese ou il aurait ete modifie. N'imprimez ce message que si necessaire, pensez a l'environnement. From rkmr.em at gmail.com Tue Feb 19 23:42:01 2008 From: rkmr.em at gmail.com (rkmr.em at gmail.com) Date: Tue, 19 Feb 2008 20:42:01 -0800 Subject: SystemError: com_backpatch: offset too large Message-ID: <e04d2e90802192042p77c78e27g826ab7d72fa40600@mail.gmail.com> hi, i get this error while using web.py and cheetah. how to fix this? happens everytime regularly thanks Traceback (most recent call last): File "/home/mark/work/pop/web/webapi.py", line 313, in wsgifunc result = func() File "/home/mark/work/pop/web/request.py", line 131, in <lambda> func = lambda: handle(inp, fvars) File "/home/mark/work/pop/web/request.py", line 61, in handle return tocall(*([x and urllib.unquote(x) for x in args] + fna)) File "/home/mark/work/pop/user.py", line 127, in proxyfunc return func(self, *args, **kw) File "./code.py", line 1491, in GET return web.render("newview.html") File "/home/mark/work/pop/web/cheetah.py", line 89, in render compiled_tmpl = _compiletemplate(template, base=base, isString=isString) File "/home/mark/work/pop/web/utils.py", line 286, in __call__ self.cache[key] = self.func(*args, **keywords) File "/home/mark/work/pop/web/cheetah.py", line 37, in __compiletemplate exec str(tmpl_compiler) in execspace SystemError: com_backpatch: offset too large From paul at boddie.org.uk Tue Feb 12 19:14:00 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 12 Feb 2008 16:14:00 -0800 (PST) Subject: bluetooth file transfer in python References: <77f0ab72-04fd-4853-a2f7-946eb001a082@i12g2000prf.googlegroups.com> Message-ID: <9912d89e-b8cb-4bc4-851e-f569811cc239@s37g2000prg.googlegroups.com> On 12 Feb, 10:50, chartsoft <charts... at cwcom.net> wrote: > I am a teacher and need to set up a computer with a bluetooth dongle > to poll for mobile phones with bluetooth switched on in the area then > send them a jpg file. I guess you'd use OBEX to send the file, specifically using the "push" mode of OBEX. Various tools such as hcitool and sdptool (found on GNU/ Linux distributions) and their counterparts exposed by Python libraries such as PyBluez [1] would be appropriate for scanning for devices. > I understand that python is capeable of this. > > 1.) is it worth learning python to do this or can someone out there do > it for me for a v small fee? > > 2.) If I am going to do it can anyone give me pointers in the best way > to do it so I do not spend hours wasting time. I've previously done OBEX-related things, mostly fetching things from mobile phones, using the obexftp program [2] which is part of the OpenOBEX project [3]. Naturally, you can call the obexftp program from Python and interpret the responses and exit codes using functions in the os, popen2 and subprocess modules. I believe that obexftp also supports "push" mode, but you could probably find something else related to OpenOBEX if it does not. Since Bluetooth communications are supported using sockets in GNU/ Linux distributions and in Python (provided that the Bluetooth support is detected and configured), you could communicate with phones using plain network programming, but this would probably require you to implement the OBEX protocols yourself - not a straightforward task for a number of reasons, including one I mention below. Thus, it's probably easier to go with obexftp at least initially. There are a number of awkward things with obexftp and OpenOBEX, however. Some phones do not follow the "standards" and the maintainer of OpenOBEX wouldn't or just didn't include support for various deviating Sony Ericsson phones, for example, thus requiring me to patch the library myself. Although there may be a Python wrapper for OpenOBEX, it's easier to just call obexftp as mentioned above, but this means that you're limited to what that program can do. Finally, and most significantly, OBEX isn't a totally free standard: if you didn't already get the standards documents while they were freely available, you now have to sign up with the quaintly named Infrared Data Association [4] - a "pay to play" organisation with restrictive redistribution terms on their specifications. Although I'd recommend that anyone doing brand new stuff with mobile devices just uses real standards instead of OBEX, I doubt that you have the choice. Anyway, I hope that this helps you understand the subject area a bit more. Paul P.S. It does also occur to me that desktop environments like KDE have Bluetooth controls which could be automated in some way in order to send files, but I haven't investigated this at all. [1] http://org.csail.mit.edu/pybluez/ [2] http://triq.net/obexftp.html [3] http://dev.zuckschwerdt.org/openobex/ [4] http://www.irda.org/ From castironpi at gmail.com Fri Feb 15 20:54:46 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 15 Feb 2008 17:54:46 -0800 (PST) Subject: call 'the following function' using decorators References: <4881cc78-85cc-4cf4-8e70-8089374d08f9@v17g2000hsa.googlegroups.com> <mailman.684.1202839520.9267.python-list@python.org> <d21274ef-5221-4453-8ffb-f34109148790@q21g2000hsa.googlegroups.com> <f65ee54f-6fa7-450b-86e2-797dfb1f202c@j20g2000hsi.googlegroups.com> Message-ID: <2050a2fa-0026-4923-9e5f-d3b4b53e4959@e25g2000prg.googlegroups.com> > > > > I assert it's easier to write: > > > > > start_new_thread( this_func ) > > > > def thrA(): > > > > ? ? normal_suite() > > > > > than > > > > > def thrA(): > > > > ? ? normal_suite() > > > > start_new_thread( thrA ) > > > > > If you don't, stop reading. Nothing beats if forkthread(): but what are the chances of getting it in Python? From jeff at schwabcenter.com Wed Feb 13 15:07:30 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Wed, 13 Feb 2008 12:07:30 -0800 Subject: OT: Speed of light In-Reply-To: <47b34916$0$1342$834e42db@reader.greatnowhere.com> References: <mailman.633.1202748971.9267.python-list@python.org> <W7qdnbVwRuMhWy3anZ2dnUVZ_tCrnZ2d@speakeasy.net> <C42dnQO3-s6BVS3anZ2dnUVZ_o_inZ2d@comcast.com> <6f-dnfwZwvz6Ui3anZ2dnUVZ_oOnnZ2d@speakeasy.net> <QcadnXHHAflcSS3anZ2dnUVZ_hGdnZ2d@comcast.com> <mailman.665.1202803393.9267.python-list@python.org> <ebWdnf1w2af9yyzanZ2dnUVZ_hadnZ2d@speakeasy.net> <13r2p6aivk1no9a@corp.supernews.com> <ENSdnam5yck27CzanZ2dnUVZ_judnZ2d@speakeasy.net> <880dece00802121311n77f73515ve7db8a931825d958@mail.gmail.com> <mailman.706.1202884863.9267.python-list@python.org> <FfKdnR-55_jZsS7anZ2dnUVZ_sKqnZ2d@comcast.com> <87abm4g1tw.fsf@mulj.homelinux.net> <5LednYnShMTspS7anZ2dnUVZ_ternZ2d@comcast.com> <47b34916$0$1342$834e42db@reader.greatnowhere.com> Message-ID: <tIKdnccaM9p50C7anZ2dnUVZ_sWdnZ2d@comcast.com> David H Wild wrote: > In article <5LednYnShMTspS7anZ2dnUVZ_ternZ2d at comcast.com>, > Jeff Schwab <jeff at schwabcenter.com> wrote: >> We (Americans) all measure our weight in pounds. People talk about how >> much less they would weigh on the moon, in pounds, or even near the >> equator (where the Earth's radius is slightly higher). > > Their weight on the moon would be exactly the same as on earth if they used > a balance with weights on the other side of the fulcrum. That's true, because they would really be indirectly measuring mass. By "weight," though, most people mean the force exerted by gravity. From steve at holdenweb.com Tue Feb 12 18:50:49 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 12 Feb 2008 18:50:49 -0500 Subject: ways to declare empty set variable In-Reply-To: <874pcdzsho.fsf@benfinney.id.au> References: <56a14$47b1a306$839b8704$9583@news2.tudelft.nl> <f30e545f-4485-4c0a-a9b2-476939818bc6@y5g2000hsf.googlegroups.com> <5099c$47b1a77b$839b8704$11089@news2.tudelft.nl> <7xhcgd7tof.fsf@ruckus.brouhaha.com> <719e7c26-7d52-4b78-875c-fc7d5ca32f4e@s19g2000prg.googlegroups.com> <874pcdzsho.fsf@benfinney.id.au> Message-ID: <fotbck$8tn$1@ger.gmane.org> Ben Finney wrote: [...] > > Note that '()' is syntactically null. Parentheses don't declare a > tuple literal, commas do. Parentheses are for grouping within > expressions, not specifying type. > Tell that to the interpreter: >>> type(()) <type 'tuple'> >>> tuple() is () True >>> regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From steven.klass at gmail.com Fri Feb 22 12:20:15 2008 From: steven.klass at gmail.com (rh0dium) Date: Fri, 22 Feb 2008 09:20:15 -0800 (PST) Subject: Simple - looking for a way to do an element exists check.. Message-ID: <d45626f2-99f6-42cc-b6fe-d109c114cf2f@n77g2000hse.googlegroups.com> Hi all, I have a simple list to which I want to append another tuple if element 0 is not found anywhere in the list. element = ('/smsc/chp/aztec/padlib/5VT.Cat', '/smsc/chp/aztec/padlib', '5VT.Cat', (33060)) element1 = ('/smsc/chp/aztec/padlib/5VT.Cat2', '/smsc/chp/aztec/padlib', '5VT.Cat2', (33060)) a = [ ('/smsc/chp/aztec/padlib/5VT.Cat', '/smsc/chp/aztec/padlib', '5VT.Cat', (33060)), ('/smsc/chp/aztec/padlib/padlib.TopCat%', '/smsc/chp/aztec/padlib', 'padlib.TopCat%', (33204)), ('/smsc/chp/aztec/padlib/Regulators.Cat%', '/smsc/chp/aztec/padlib', 'Regulators.Cat%', (33204))] So my code would look something like this. found = False for item in a: if item[0] == element[0] found = True break if not found: a.append(element) But this is just ugly - Is there a simpler way to interate over all items in a without using a found flag? Thanks From bborcic at gmail.com Tue Feb 5 04:47:09 2008 From: bborcic at gmail.com (Boris Borcic) Date: Tue, 05 Feb 2008 10:47:09 +0100 Subject: future multi-threading for-loops In-Reply-To: <2945ae3c-31ca-49e0-b623-24d5fb8050d8@f10g2000hsf.googlegroups.com> References: <5ba19668-4eb1-430c-b1e6-d1b17de33811@s13g2000prd.googlegroups.com> <02514c37-8cad-4e3f-892c-58a309d6d4a7@s19g2000prg.googlegroups.com> <27eca1d3-2e79-428e-9fc8-d75434efd2d5@l1g2000hsa.googlegroups.com> <2945ae3c-31ca-49e0-b623-24d5fb8050d8@f10g2000hsf.googlegroups.com> Message-ID: <47a830d2$1_4@news.bluewin.ch> castironpi at gmail.com wrote: > On Feb 5, 12:26 am, Gabriel Genellina <gagsl-... at yahoo.com.ar> wrote: >> On 5 feb, 03:46, castiro... at gmail.com wrote: >> >>> Some timing stats: On Windows XP, Python 3.0a2. (...) >>> Are threads an OS bottleneck? >> I don't understand your threading issues, but I would not use 3.0a2 >> for benchmarking anything (except benchmarking Python 3.0 itself). >> AFAIK the developers are first trying to get it right and stable; >> speed issues will be addressed later. >> >> -- >> Gabriel Genellina > > Multi-threaded control flow is a worthwhile priority. What he said is that you should apply the idea to the mixing of your thread of benchmarking with the thread of python development. From bj_666 at gmx.net Thu Feb 7 02:28:58 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 7 Feb 2008 07:28:58 GMT Subject: getting all user defined attributes of a class References: <305a63f1-70b0-4234-ac6f-4fa1a43b5c78@e10g2000prf.googlegroups.com> <60upr7F1sat47U1@mid.uni-berlin.de> <5489736a-dc8e-47f3-8d5e-4a7d24dc37bd@j20g2000hsi.googlegroups.com> <60us7tF1sishaU1@mid.uni-berlin.de> <5e27bc41-ed33-4635-9818-3fccf4db2a55@s12g2000prg.googlegroups.com> Message-ID: <60vq9qF1sat47U2@mid.uni-berlin.de> On Wed, 06 Feb 2008 15:16:26 -0800, Amit Gupta wrote: > On Feb 6, 2:55 pm, "Diez B. Roggisch" <de... at nospam.web.de> wrote: >> Amit Gupta schrieb: >> > I should make class A as: >> > class A (object) : >> > x = 1 >> >> > Now, x is class attribute and I am looking for some-way to filter non- >> > user-defined attributes. >> >> > e.g.g if I do >> > for attr in a.__dict__ : >> > print attr >> >> > I will also get >> >> > __module__, __weakref__ and others including "x" >> >> Just create an empty class, gather all attribute names from that and >> then subtract that set of names from the names you get from a "real" class. >> >> Dize > > Fine. This is a hack. I am looking if python language itself provides > any built-in function for this. E.g.: Why is that a hack!? What about: In [369]: def is_special_name(name): .....: return name.startswith('__') and name.endswith('__') .....: In [370]: filter(lambda m: not is_special_name(m[0]), inspect.getmembers(A)) Out[370]: [('x', 1)] > When I do help on some built-in function, it displays that function is > built_in. Can that information get accessed using a function? (now, > don't ask me to store help-output in buffer and grep for built-in). Yes but it is not built-in. Have a look at the `inspect` module. What's the use case? Ciao, Marc 'BlackJack' Rintsch From samuraiblog at gmail.com Mon Feb 18 03:09:02 2008 From: samuraiblog at gmail.com (samuraisam) Date: Mon, 18 Feb 2008 00:09:02 -0800 (PST) Subject: Current Fastest Python Implementation? Message-ID: <728901d3-edb8-4c7a-b823-7065a9b1250e@e6g2000prf.googlegroups.com> Has anyone done any recent testing as to which current python implementation is the quickest? Perhaps for Django development - though the current one certainly is fast (and I doubt micro optimizations would make much difference in overall performance). Regardless - have those pypy folks made a faster implementation, or the jython folks? Or the .NET implementation? Sam From gagsl-py2 at yahoo.com.ar Tue Feb 12 17:12:12 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 12 Feb 2008 20:12:12 -0200 Subject: Getting a Foothold on the IDLE Debugger References: <_V9sj.123$tW.35@nlpi070.nbdc.sbc.com> <e0018a84-a287-45b2-95c0-c029a81d9639@s12g2000prg.googlegroups.com> <kVasj.289$Mh2.194@nlpi069.nbdc.sbc.com> Message-ID: <op.t6fmmm0ax6zn5v@gabriel2.softlabbsas.com.ar> En Tue, 12 Feb 2008 04:23:17 -0200, W. Watson <wolf_tracks at invalid.com> escribi?: > BTW, what's with the close and exit options on the File menu? They both > dump > me out of IDLE. Odd. Try File|New > Any idea of whether I can "glue" the File-?Open to a > particular folder? Mmm, no. But it remembers the last used directory. > Any other similar programs with a better user interface for beginners? Try PyScripter (Windows only, I think). People say that SPE (Stani's Python Editor, multiplatform) is good too. -- Gabriel Genellina From rcdailey at gmail.com Fri Feb 1 11:12:59 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 1 Feb 2008 10:12:59 -0600 Subject: Will Python on day replace MATLAB????????????????????????????????????????????????????? In-Reply-To: <neaa75-ibe.ln1@strongwill.g2ctech> References: <mailman.456.1201802778.9266.python-list@python.org> <27CC3060AF71DA40A5DC85F7D5B70F380239F7FC@AWMAIL04.belcan.com> <mailman.128.1201829924.9267.python-list@python.org> <neaa75-ibe.ln1@strongwill.g2ctech> Message-ID: <496954360802010812j672b35e1vb99ba918b564@mail.gmail.com> > > This is not part of his Masters... :-) Lmfao.... -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080201/9068baf6/attachment.html> From stefan_ml at behnel.de Sat Feb 2 11:16:53 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 02 Feb 2008 17:16:53 +0100 Subject: Mysterious xml.sax Encoding Exception In-Reply-To: <mailman.204.1201967743.9267.python-list@python.org> References: <mailman.204.1201967743.9267.python-list@python.org> Message-ID: <47A49775.5090503@behnel.de> Peck, Jon schrieb: > Yes, the characters were from the 0-127 ascii block but encoded as utf-16, so there is a null byte with each nonzero character. I.e., \x00?\x00x\x00m\x00l\x00 > > Here is something weird I found while experimenting with ElementTree with this same XML string. > > Consider the same XML as a Python Unicode string, so it is actually encoded as utf-16 and as a string containing utf-16 bytes. That is > u'<?xml version="1.0" encoding="UTF-16" st' ... > or > '\xff\xfe<\x00?\x00x\x00m\x00l\x00 \x00v\x00e\x00r\x00s\x00i\x00o\x00n\x00=\x00"\x001\x00.\x000\x00"\x00'... > > So if these are x and y > y = x.encode("utf-16") > > The actual bytes would be the same, I think, although y is type str and x is type unicode. No. The internal representation of unicode characters is platform dependent, and is either 2 or 4 bytes per character. If you want UTF-16, use ".encode()". > xml.sax.parseString documentation says > > parses from a buffer string received as a parameter, > > so one might imagine that either x or y would be acceptable, and the bytes would be interpreted according to the encoding declaration in the byte stream. > > And, in fact, both do work with xml.sax.parseString (at least for me). With etree.parse(StringIO.StringIO...) though, only the str form works. Don't try. Serialised XML is bytes, not characters. Stefan From jabar004 at gmail.com Wed Feb 13 09:14:58 2008 From: jabar004 at gmail.com (Juan_Pablo) Date: Wed, 13 Feb 2008 06:14:58 -0800 (PST) Subject: Word document accessing using python References: <1436398c-260e-4dd1-a735-3df4da894231@v46g2000hsv.googlegroups.com> Message-ID: <1a9a7ccf-490c-4911-92a0-3faefea4baec@e6g2000prf.googlegroups.com> On 13 feb, 10:40, Hari <p.r.hari... at gmail.com> wrote: > Hello, > I want to fetch some data from the work document and to fill it inside > excel sheet. For this I want to perform opening word documents and do > some string manipulations for extracting data and to fill it inside > excel sheet. > Can any one help in this by saying how to do this or by giving some > link where I can find some hints. > > Thanks in advance, > Hari I have a similar problem look this http://www.thescripts.com/forum/thread39591.html http://www.velocityreviews.com/forums/t330073-opening-ms-word-files-via-python.html I hope you can supplement with more information From asmodai at in-nomine.org Sun Feb 24 15:21:16 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Sun, 24 Feb 2008 21:21:16 +0100 Subject: Developing Techniques (and naming conventions) In-Reply-To: <f9d5d06b-4874-44ea-8533-0ac7feeb8e11@o10g2000hsf.googlegroups.com> References: <e053113a-ab66-4c50-86f1-56431ddfb3de@q33g2000hsh.googlegroups.com> <mailman.1170.1203876385.9267.python-list@python.org> <f9d5d06b-4874-44ea-8533-0ac7feeb8e11@o10g2000hsf.googlegroups.com> Message-ID: <20080224202116.GM66273@nexus.in-nomine.org> -On [20080224 20:01], Adekoba (adekoba at gmail.com) wrote: >I don't think moving food.py's code to __init__.py would work out to >well, because then how would I run the script? import food Which in turn has something like this in food/__init__.py: from food.cheese import gouda from food.ham import parma __all__ = ['gouda', 'parma'] and in turn in your script you can now use food.gouda and food.parma. Unless I totally misunderstood what you are trying to achieve. -- Jeroen Ruigrok van der Werven <asmodai(-at-)in-nomine.org> / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ We have met the enemy and they are ours... From noname9968 at gmail.com Sat Feb 9 10:54:41 2008 From: noname9968 at gmail.com (Alex) Date: Sat, 09 Feb 2008 18:54:41 +0300 Subject: Edit Python code programmatically In-Reply-To: <ac2200130802090622y24765884yd510da26d263a688@mail.gmail.com> References: <47AD90B5.9030504@gmail.com> <ac2200130802090347u264058c3yca13fa114ff12b1f@mail.gmail.com> <47AD983B.8050908@gmail.com> <mailman.554.1202560349.9267.python-list@python.org> <eb0a95f5-444b-4167-84f6-d712770a1bf0@l16g2000hsh.googlegroups.com> <ac2200130802090517r5ce2019docddfb92a55a822dc@mail.gmail.com> <47ADAEA2.6090702@gmail.com> <ac2200130802090622y24765884yd510da26d263a688@mail.gmail.com> Message-ID: <47ADCCC1.3030807@gmail.com> Guilherme Polo wrote: > 2008/2/9, Alex <noname9968 at gmail.com>: > >> Guilherme Polo wrote: >> > 2008/2/9, Arnaud Delobelle <arnodel at googlemail.com>: >> > >> >> On Feb 9, 12:32 pm, "Guilherme Polo" <ggp... at gmail.com> wrote: >> >> > 2008/2/9, Alex <noname9... at gmail.com>: >> >> > >> >> > > Guilherme Polo wrote: >> >> > > > 2008/2/9, Alex <noname9... at gmail.com>: >> >> >> >> >> >> > > >> Which library could you recommend to perform simple editing of Python >> >> > > >> code (from Python program)? For example, open *.py file, find specific >> >> > > >> function definition, add another function call inside, find existing >> >> > > >> call and change parameter value, etc. >> >> > > > You are after inspect, it is included with python. >> >> > >> >> > > Yes, I forgot to mention - I'm new to Python. I didn't necessary mention >> >> > > 3rd party library. Simply such wasn't mentioned in library review and >> >> > > tutorials, so I didn't know of it. What's the module's name? >> >> > >> >> >> >> >> >>> inspect is a module, inspect is the name. It is not a module for >> >>> >> >> > editing Python code per se, but it will help with the other part. >> >> >> >> >> >> I don't think the OP wants to edit python code *objects*, rather he >> >> wants to edit python *source* code programmatically. Inspect is not >> >> the tool for this. >> >> >> > >> > I didn't tell him to use inspect to edit python code, I said it was >> > useful for the other part. The other part, as he mentioned on his >> > email is: "find specific >> > function definition, add another function call inside, find existing >> > call". >> >> Sorry but I said "in *.py file", meaning that file isn't executed to >> edit objects in memory. It's instead saved in modified form, possibly to >> be edited by user. Guess it's a common task for visual GUI editors and >> any visual programming tools. >> >> > > By visual GUI editors I will assume GUI designer tools. These tend to > not generate direct python code, glade-2 used to but glade-3 doesn't > anymore. Other tools like XRCed generates xrc, wxGlade has an option > to generate .xrc too, Qt Designer generates .ui and .qrc, Glade-3 > generates .glade file, Gazpacho generates .glade, or a gazpacho format > or gtkbuilder format. In all these, it is recommended to use something > to work with the generated code, like libglade, wx.xrc and PyQt has > tools to convert .ui and .qrc to python modules but they don't affect > your custom code (it is also possible to load .ui using uic module). > > With this we come back to my first email, where I told you it is not > recommended to generate direct python code, especially if you are > doing the kind of things you just mentioned. If you still want to > generate python code, from some other source, inspect can be helpful. Thank you for detailed reply... but I still want to generate python code. By the way, Python Package Index references code generators able to generate Python code (http://pypi.python.org/pypi?:action=browse&show=all&c=409), which I'll inspect later (especially their ability to *edit* code). Inspect might be useful too. From steve at holdenweb.com Tue Feb 26 12:13:38 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 26 Feb 2008 12:13:38 -0500 Subject: How about adding rational fraction to Python? In-Reply-To: <20080226100824.fdc81ac7.darcy@druid.net> References: <b2b884df-b499-4740-9d21-cae87bbd790d@q77g2000hsh.googlegroups.com> <mailman.1169.1203875215.9267.python-list@python.org> <f4443376-04a0-414e-9eba-149bf9779bef@34g2000hsz.googlegroups.com> <649ac8a9-ae09-4e9b-85c2-f37043af21fd@28g2000hsw.googlegroups.com> <edd61692-2b00-405c-adfe-7f5224097e95@e10g2000prf.googlegroups.com> <ead37b53-5174-4a54-ae36-f0e1be1dd065@z17g2000hsg.googlegroups.com> <fpt11h$uob$1@aioe.org> <0d1955fc-762c-44e1-a5d8-372c71458455@p25g2000hsf.googlegroups.com> <36204e6f-0d82-449b-8ca5-c819ace9a55a@p73g2000hsd.googlegroups.com> <f32fa9e5-feb2-4d30-845a-447dbce6b19a@p73g2000hsd.googlegroups.com> <9503b14b-7bd5-42b4-b3f7-673d0ebd7feb@c33g2000hsd.googlegroups.com> <602ac27c-4aaa-49b2-bee2-1e0e0c705983@i7g2000prf.googlegroups.com> <1204034122.3318.3.camel@aalcdl07.lib.unc.edu> <mailman.1277.1204036207.9267.python-list@python.org> <f55a8ef7-2ed8-4963-b485-04d9f20414d0@34g2000hsz.googlegroups.com> <20080226100824.fdc81ac7.darcy@druid.net> Message-ID: <fq1hbs$pf8$2@ger.gmane.org> D'Arcy J.M. Cain wrote: > On Tue, 26 Feb 2008 06:45:45 -0800 (PST) > Carl Banks <pavlovevidence at gmail.com> wrote: >> On Feb 26, 9:29 am, "D'Arcy J.M. Cain" <da... at druid.net> wrote: >>> If 3/4 ever returned 0.75 in any language I would drop that language. >> Have fun dropping Python, then, chief. Integer division with / is >> already deprecated, can be disabled ever since Python 2.4, and will be >> wholly removed in Python 3.0. > > I have not been following Python development that closely lately so I > was not aware of that. I guess I won't be going to Python 3 then. It's > great that Python wants to attract young, new programmers. Too bad > about us old farts I guess. > > How soon before 2.x is completely deprecated and I have to become a > Walmart greeter? > I'm guessing at least four years: 2.6 will com out at the same time as 3.1, and there will definitely be a 2.7 release. After that you may indeed be working for Walmart, though do remember that 1.5.2 is still a perfectly viable language ten years after its release. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From mal at egenix.com Thu Feb 7 10:33:48 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Thu, 07 Feb 2008 16:33:48 +0100 Subject: Must COMMIT after SELECT In-Reply-To: <47AB07CF.6010804@holdenweb.com> References: <47a76661$0$36336$742ec2ed@news.sonic.net> <mailman.380.1202310266.9267.python-list@python.org> <ff428fb6-6729-431a-a09c-63c0fbfdfd86@y5g2000hsf.googlegroups.com> <mailman.429.1202370763.9267.python-list@python.org> <ff381e58-70f9-4ec4-a9b1-43a6cc6d5ed7@l32g2000hse.googlegroups.com> <47AB07CF.6010804@holdenweb.com> Message-ID: <47AB24DC.4080104@egenix.com> On 2008-02-07 14:29, Steve Holden wrote: > Paul Boddie wrote: >> With PostgreSQL, my impression is that the intended way of using >> cursors is not entirely compatible with the DB-API: you declare >> cursors only when you know what the query will be, not in advance, and >> they can only be used with certain kinds of operations. As far as I >> recall, pyPgSQL supports cursors fairly transparently, albeit through >> various ad-hoc measures, whereas psycopg2 only does so for "named >> cursors" - a concept missing from the DB-API as far as I can see. >> > Yes, unfortunately the nomenclature of the DB API conflicts with that of > SQL'S DECLARE CURSOR, where the named cursor is effectively a sequence > of query results that (under certain isolation levels and patterns of > usage) can reflect database changes as they occur. Different > implementers have chosen different relationships between DB API cursors > and SQL cursors since it was introduced in the SQL 92 standard. > > I believe, without documentary justification, that named cursors were > introduced into SQL to support stored procedures, and therefore weren't > intended to be used for queries whose results were communicated outside > the server. Cursors defined using DECLARE CURSOR usually live in the scope of the database engine. They are different from the cursors defined and used with the database APIs. MS even warns against mixing them: http://msdn2.microsoft.com/en-us/library/aa172576(SQL.80).aspx The Python DB-API is defined at the database API level, so the same applies in the context of DB-API cursors. In practice, I've not had problems with accessing named cursors using DB-API cursors. The main reason for the MS warning is that cursors can be used for lots of interesting optimizations such as auto-updating result sets and scrolling, positioned updates or deletions, etc. The DB-API doesn't expose all these nifty features, so doesn't easily run into trouble. mxODBC has support for named cursors that you can later use for positioned updates. You declare the name of the cursor when creating it: cursor1 = connection.cursor('mycursor') cursor1.execute('select id, name, value from mytable') # Position the mycursor on row 10 cursor1.fetchmany(10) # Update row 10 cursor2 = connection.cursor() cursor2.execute('update mytable set value = ? where current of mycursor') cursor1.close() cursor2.close() However, it's usually better to do updates in the classical way, ie. by referencing a primary key. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Feb 07 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From stephan.diehl at gmx.net Fri Feb 15 02:23:01 2008 From: stephan.diehl at gmx.net (Stephan Diehl) Date: Fri, 15 Feb 2008 08:23:01 +0100 Subject: appwsgi References: <c24ee7e2-360d-488b-8f09-3d73bf875fe7@i29g2000prf.googlegroups.com> Message-ID: <fp3ekl$415$00$1@news.t-online.com> gert wrote: > can my http://appwsgi.googlecode.com/ be on the http://wsgi.org/ page > somewhere please :) you are free to register yourself on wsgi.org and put a link to your software at the appropriate place. It's a wiki, after all. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Feb 7 04:05:20 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 07 Feb 2008 10:05:20 +0100 Subject: Adding properties to an instance In-Reply-To: <cf80b872-a053-4d79-97d9-b45cb57ee48c@e10g2000prf.googlegroups.com> References: <a476484f-cb72-4462-9d1a-640e5db07211@c23g2000hsa.googlegroups.com> <55cb97bc-ce13-4abf-a1be-911d7c3f3c6b@u10g2000prn.googlegroups.com> <cf80b872-a053-4d79-97d9-b45cb57ee48c@e10g2000prf.googlegroups.com> Message-ID: <47aac9bf$0$1157$426a34cc@news.free.fr> dg.google.groups at thesamovar.net a ?crit : > On Feb 6, 11:09 pm, "bruno.desthuilli... at gmail.com" > <bruno.desthuilli... at gmail.com> wrote: >> While this is technically possible (I tried a couple years ago), it >> requires hacking the __getattribute__ method, which is something I >> would not recommand, not only because it can be tricky, but mostly >> because this is a very critical path wrt/ perfs. (IIRC it also >> required using custom descriptors, but I'm not really sure about this >> last point). > > Performance is pretty important for the class I'm designing so I think > __getattribute__ is probably out. The computed properties are only > infrequently accessed, but using __getattribute__ slows everything > down, right? Indeed - it *is* the attribute lookup mechanism. Better to leave it alone. >> Before new-style classes, we used the __getattr__/__setattr__ hooks >> for computed attributes. While this approach is now a bit abandonned >> in favor of descriptors (properties or custom ones), it still works >> fine, and is probably the best solution to your problem. > > Ah, I didn't know about these - it looks as though they might be just > the thing since it seems they're only called after all the other > methods fail. Right. > That looks like there would be no performance hit, I > wouldn't need to mess around with dynamically changing the class, and > it would automatically deal with the (irritating) feature of having to > check if there is already something in the object's dir() with that > name. I'll look into this tomorrow - I hope this feature isn't going > to be removed in future versions of Python? I really don't think so. It's still has it's use for automatic delegation. And, as is the case here, for per-instance computed attributes. As a side note: the naming symetry between __getattr__ and __setattr__ is a gotcha, since __setattr__ is mostly symetric to __getattribute__ - IOW, customizing __setattr__ is a bit tricky. The naive approach, ie: class Parrot(object): def __setattr__(self, name, val): self.name = val will indeed go into infinite recursion (or would, if the interpreter didn't stop it after a while) The solution is of course to call on the parent class's __setattr__: class Ni(object): def __setattr__(self, name, val): object.__setattr__(self, name, value) HTH From parmaka2 at gmail.com Sat Feb 16 00:59:16 2008 From: parmaka2 at gmail.com (Python_Doctor) Date: Fri, 15 Feb 2008 21:59:16 -0800 (PST) Subject: Where can I get the module MyUtils? Message-ID: <4aed89a3-95d4-4ee8-96c2-74556abe17ef@s37g2000prg.googlegroups.com> I inherited a piece of python code which imports "MyUtils" i.e. it has a line: import MyUtils When I execute the code I get: ImportError: No module named MyUtils I assume the code is looking for another module called MyUtils.py. Is this a standard Python module? Where can I download this module from? Many thanks Monty From jared.grubb at gmail.com Wed Feb 6 15:43:37 2008 From: jared.grubb at gmail.com (Jared Grubb) Date: Wed, 6 Feb 2008 12:43:37 -0800 Subject: Adding properties to an instance Message-ID: <925822270802061243y704da921me72c3cd42fc65be7@mail.gmail.com> Here's one way of doing what you're asking... I would suggest using __getattribute__ and __setattr__ to dispatch the methods to the custom class you invent that holds all those properties. For example (I simplified your makeprops into __init__ just to keep the example short, but you can probably see the idea here..) class A(object): def __init__(self, **kw): class _PropHolder(object): pass for k,v in kw.items(): setattr(_PropHolder, k, property(fget=itemgetter(k))) self._custom_props = _PropHolder() def __getattribute__(self, attr): try: return getattr(self._custom_props, attr) except AttributeError: return getattr(self, attr) def __setattr__(self, attr, val): if hasattr(self._custom_props, attr): setattr(self._custom_props, attr, val) else: setattr(self, attr, val) def __delattr__(self, attr): if hasattr(self._custom_props, attr): delattr(self._custom_props, attr) else: delattr(self, attr) On 6 Feb 2008, at 12:06, dg.google.groups at thesamovar.net wrote: Hi all, So I understand that properties belong to a class not an instance, but nonetheless I want to add properties to an instance. I have a class which when an instance is created runs some fairly complicated code and produces a set of names which I'd like to be able to access via properties. At the moment, I'm using something like obj.getvar(name) but I'd like to be able to write obj.name. (Note that they can't be just standard attributes because they only get computed when they are accessed.) I could generate functions like obj.name() but I want it to be obj.name instead. The solution I've come up with is to create a new class for each object which is just the real class with some extra properties, and then dynamically change the class of the object to this new class. This seems to work, but I wonder if (a) there is a nicer solution than the one I'll post below, (b) if there are any dangers or pitfalls of this approach. The obvious difficulty is with derived classes. At the moment, I'm insisting that a derived class has to call a makeprops() method to create the properties. It's kind of similar to this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/197965 but that recipe has a much simpler situation in which the properties and values are known at the time of the creation of the object (by contrast, I don't know what the properties are until the end of the __init__ method). Any thoughts? Code below to illustrate my approach. import warnings from operator import itemgetter class A(object): def __init__(self,**kwds): self._kwds = kwds self.makeprops() def __getitem__(self,i): return self._kwds[i] def makeprops(self): if not hasattr(self,'_madeprops'): self._madeprops = set() self._failedprops = set() class _A(self.__class__): pass for k,v in self._kwds.items(): if not k in self._madeprops and k in dir(self): if not k in self._failedprops: warnings.warn("Cannot create property "+k+", already used in object "+str(self),RuntimeWarning) self._failedprops.add(k) else: setattr(_A,k,property(fget=itemgetter(k))) self._madeprops.add(k) self.__class__ = _A class B(A): def __init__(self,**kwds): super(B,self).__init__(**kwds) self.makeprops() class C(A): def __init__(self,**kwds): self._kwds = kwds a = A(x=1) b = B(x=2,makeprops=3) c = C(x=3) print isinstance(a,A), isinstance(a,B), isinstance(a,C) # True False False print isinstance(b,A), isinstance(b,B), isinstance(b,C) # True True False print isinstance(c,A), isinstance(c,B), isinstance(c,C) # True False True print a.__class__ # <class '__main__._A'> print b.__class__ # <class '__main__._A'> print c.__class__ # <class '__main__.C'> print a.x # 1 print b.x # 2 print b.makeprops # <bound method _A.makeprops of <__main__._A object at 0x00A86810>> try: print c.x # raises exception except AttributeError: print "c has no element x" c.makeprops() print c.x # 3 print a.__class__ # <class '__main__._A'> print b.__class__ # <class '__main__._A'> print c.__class__ # <class '__main__._A'> --- Dan Goodman http://thesamovar.net/contact -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080206/18c72ae5/attachment.html> From electronixtar at gmail.com Sun Feb 24 23:23:20 2008 From: electronixtar at gmail.com (est) Date: Sun, 24 Feb 2008 20:23:20 -0800 (PST) Subject: n00b with urllib2: How to make it handle cookie automatically? References: <f5942aa6-b731-4b02-98fd-fbbf05005961@n58g2000hsf.googlegroups.com> <87pruorfxb.fsf@merkury.smsnet.pl> <3632dae4-24a7-4f2e-96f0-c3bcd53cf8ac@t66g2000hsf.googlegroups.com> <919d2b8c-d6ec-4940-97d0-4c9b81ba1f32@o10g2000hsf.googlegroups.com> Message-ID: <b4b91102-a793-465c-bea1-446e19152fd1@s8g2000prg.googlegroups.com> On Feb 25, 5:46?am, 7stud <bbxx789_0... at yahoo.com> wrote: > On Feb 24, 4:41?am, est <electronix... at gmail.com> wrote: > > > > > > > On Feb 23, 2:42?am, Rob Wolfe <r... at smsnet.pl> wrote: > > > > est <electronix... at gmail.com> writes: > > > > Hi all, > > > > > I need urllib2 do perform series of HTTP requests with cookie from > > > > PREVIOUS request(like our browsers usually do ). Many people suggest I > > > > use some library(e.g. pycURL) instead but I guess it's good practise > > > > for a python beginner to DIY something rather than use existing tools. > > > > > So my problem is how to expand the urllib2 class > > > > > from cookielib import CookieJar > > > > class SmartRequest(): > > > > ? ? cj=CookieJar() > > > > ? ? def __init__(self, strUrl, strContent=None): > > > > ? ? ? ? self.Request ? ?= ? urllib2.Request(strUrl, strContent) > > > > ? ? ? ? self.cj.add_cookie_header(self.Request) > > > > ? ? ? ? self.Response ? = ? urllib2.urlopen(Request) > > > > ? ? ? ? self.cj.extract_cookies(self.Response, self.Request) > > > > ? ? def url > > > > ? ? def read(self, intCount): > > > > ? ? ? ? return self.Response.read(intCount) > > > > ? ? def headers(self, strHeaderName): > > > > ? ? ? ? return self.Response.headers[strHeaderName] > > > > > The code does not work because each time SmartRequest is initiated, > > > > object 'cj' is cleared. How to avoid that? > > > > The only stupid solution I figured out is use a global CookieJar > > > > object. Is there anyway that could handle all this INSIDE the class? > > > > > I am totally new to OOP & python programming, so could anyone give me > > > > some suggestions? Thanks in advance > > > > Google for urllib2.HTTPCookieProcessor. > > > > HTH, > > > Rob- Hide quoted text - > > > > - Show quoted text - > > > Wow, thank you Rob Wolfe! Your reply is shortest yet most helpful! I > > solved this problem by the following code. > > > class HTTPRefererProcessor(urllib2.BaseHandler): > > ? ? """Add Referer header to requests. > > > ? ? This only makes sense if you use each RefererProcessor for a > > single > > ? ? chain of requests only (so, for example, if you use a single > > ? ? HTTPRefererProcessor to fetch a series of URLs extracted from a > > single > > ? ? page, this will break). > > > ? ? There's a proper implementation of this in module mechanize. > > > ? ? """ > > ? ? def __init__(self): > > ? ? ? ? self.referer = None > > > ? ? def http_request(self, request): > > ? ? ? ? if ((self.referer is not None) and > > ? ? ? ? ? ? not request.has_header("Referer")): > > ? ? ? ? ? ? request.add_unredirected_header("Referer", self.referer) > > ? ? ? ? return request > > > ? ? def http_response(self, request, response): > > ? ? ? ? self.referer = response.geturl() > > ? ? ? ? return response > > > ? ? https_request = http_request > > ? ? https_response = http_response > > > def main(): > > ? ? cj = CookieJar() > > ? ? opener = urllib2.build_opener( > > ? ? ? ? urllib2.HTTPCookieProcessor(cj), > > ? ? ? ? HTTPRefererProcessor(), > > ? ? ) > > ? ? urllib2.install_opener(opener) > > > ? ? urllib2.urlopen(url1) > > ? ? urllib2.urlopen(url2) > > > if "__main__" == __name__: > > ? ? main() > > > And it's working great! > > > Once again, thanks everyone! > > How does the class HTTPReferrerProcessor do anything useful for you?- Hide quoted text - > > - Show quoted text - Well, it's more browser-like. Many be I should have snipped HTTPReferrerProcessor code for this discussion. From Matthew_WARREN at bnpparibas.com Tue Feb 5 12:50:05 2008 From: Matthew_WARREN at bnpparibas.com (Matthew_WARREN at bnpparibas.com) Date: Tue, 5 Feb 2008 17:50:05 +0000 Subject: App idea, Any idea on implementation? In-Reply-To: <3afa0ab2-ab4d-4e17-acbd-6c63b0f1733d@v67g2000hse.googlegroups.com> Message-ID: <OF7FE7DEB1.425485C0-ON802573E6.0061B9B9-802573E6.0061F818@bnpparibas.com> Ok, probably not the answer your after. csound can do this easily. If you doing it via python, you'll need some way of FFT analysing sample data and analysing that to get which frequencies have the most energy... although I'm sure there are some, I don't know the names of any python libs that do it... I think... not my speciality but I have played with similar stuff in the past. Matt. Internet dnhkng at googlemail.com To python-list Sent by: cc python-list-bounces+matthew.warren=uk.bnpparibas.com@ python.org Subject Re: App idea, Any idea on implementation? 04/02/2008 21:11 thanks for the pointers! I just found a program that does more or less what I want, but I would still like to have a go myself. The link is: http://www.akoff.com/music-composer.html I gave the program a go, as there is a free trial. I found that it had a hard time doing the conversion (or I am a really bad whistler), maybe there is room for improvements. So, I know it can be done, the question is, does Python have to power to do it? And how did they actually do it anyway... -- http://mail.python.org/mailman/listinfo/python-list This message and any attachments (the "message") is intended solely for the addressees and is confidential. If you receive this message in error, please delete it and immediately notify the sender. Any use not in accord with its purpose, any dissemination or disclosure, either whole or partial, is prohibited except formal approval. The internet can not guarantee the integrity of this message. BNP PARIBAS (and its subsidiaries) shall (will) not therefore be liable for the message if modified. Do not print this message unless it is necessary, consider the environment. --------------------------------------------- Ce message et toutes les pieces jointes (ci-apres le "message") sont etablis a l'intention exclusive de ses destinataires et sont confidentiels. Si vous recevez ce message par erreur, merci de le detruire et d'en avertir immediatement l'expediteur. Toute utilisation de ce message non conforme a sa destination, toute diffusion ou toute publication, totale ou partielle, est interdite, sauf autorisation expresse. L'internet ne permettant pas d'assurer l'integrite de ce message, BNP PARIBAS (et ses filiales) decline(nt) toute responsabilite au titre de ce message, dans l'hypothese ou il aurait ete modifie. N'imprimez ce message que si necessaire, pensez a l'environnement. From ebgssth at gmail.com Thu Feb 14 07:33:53 2008 From: ebgssth at gmail.com (js) Date: Thu, 14 Feb 2008 21:33:53 +0900 Subject: Is there any Generic RSS/ATOM generator in Python? In-Reply-To: <87ve4sc80o.fsf@physik.rwth-aachen.de> References: <mailman.618.1202741279.9267.python-list@python.org> <slrnfr7pnj.6ad.te_rem_ra_ove_an_forspam@There-Are-Many-Things.consistent.org> <87ve4sc80o.fsf@physik.rwth-aachen.de> Message-ID: <a23effaf0802140433t297f58g41085826f1fbf08b@mail.gmail.com> Trivial? More than XML::Atom::Feed? http://search.cpan.org/~miyagawa/XML-Atom-0.28/lib/XML/Atom/Feed.pm On 2/14/08, Torsten Bronger <bronger at physik.rwth-aachen.de> wrote: > Hall?chen! > > > Terran Melconian writes: > > > On 2008-02-11, js <ebgssth at gmail.com> wrote: > > > >> Is there any de-fact standard RSS/ATOM generator? (especially, > >> I'd like to create Atom's) Do I have to do it myself from > >> scratch? > > > > I looked into similar issues about six months ago. My conclusion > > was that generally XML generation libraries (unlike parsers) don't > > get written, because there's little enough to them that it isn't > > seen as worth doing, and that accepted practice is to just do it > > yourself. > > > Maybe I understand you wrongly but there *is* a general XML > generator with ElementTree. I wouldn't generate XML directly but > using ElementTree to generate Atom. I did it myself three months > ago and it was really trivial. > > Tsch?, > Torsten. > > > -- > Torsten Bronger, aquisgrana, europa vetus > Jabber ID: bronger at jabber.org > (See http://ime.webhop.org for further contact info.) > > -- > http://mail.python.org/mailman/listinfo/python-list > From exarkun at divmod.com Fri Feb 15 14:40:08 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 15 Feb 2008 14:40:08 -0500 Subject: linux disc space In-Reply-To: <BeSdneewMK8LdSjanZ2dnUVZ_sDinZ2d@comcast.com> Message-ID: <20080215194008.6859.626712397.divmod.quotient.9899@ohm> On Fri, 15 Feb 2008 11:32:09 -0800, Jeff Schwab <jeff at schwabcenter.com> wrote: >Chris wrote: >> On Feb 15, 7:10 pm, DataSmash <r... at new.rr.com> wrote: >>> I simply want to capture the free disc space in a variable so that I >>> can compare changes. I'm aware of a few commands like "df -h" or "du - >>> k", but I can't figure out how to capture those values as a variable. >>> I also looked at os.statvfs(), but that output doesn't seem to make >>> any sense at all to me, knowing the size of the disc. >>> Thanks for your help! >>> R.D. >> >> import os, statvfs >> s = os.statvfs(".") >> freebytes = s[statvfs.F_BSIZE] * s[statvfs.F_BAVAIL] > >Is it worth distinguishing free bytes from available bytes? I've never >seen them differ, and I'm not sure how they ever would... > > [snip] > /: 27723000K free, 15817232K available It's common for some space to be reserved and only usable by the superuser. Jean-Paul From tenax.raccoon at gmail.com Sun Feb 3 23:06:18 2008 From: tenax.raccoon at gmail.com (Jason) Date: Sun, 3 Feb 2008 20:06:18 -0800 (PST) Subject: type, object hierarchy? References: <814a05b4-6f13-4c86-8c68-a30da06ca093@b2g2000hsg.googlegroups.com> Message-ID: <2ba95819-0699-49c6-b7e9-96d54763be52@v17g2000hsa.googlegroups.com> On Feb 3, 8:36 pm, 7stud <bbxx789_0... at yahoo.com> wrote: > print dir(type) #__mro__ attribute is in here > print dir(object) #no __mro__ attribute > > class Mammals(object): > pass > class Dog(Mammals): > pass > > print issubclass(Dog, type) #False > print Dog.__mro__ > > --output:-- > (<class '__main__.Dog'>, <class '__main__.Mammals'>, <type 'object'>) > > The output suggests that Dog actually is a subclass of type--despite > the fact that issubclass(Dog, type) returns False. In addition, the > output of dir(type) and dir(object): > > ['__base__', '__bases__', '__basicsize__', '__call__', '__class__', > '__cmp__', '__delattr__', '__dict__', '__dictoffset__', '__doc__', > '__flags__', '__getattribute__', '__hash__', '__init__', > '__itemsize__', '__module__', '__mro__', '__name__', '__new__', > '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', > '__subclasses__', '__weakrefoffset__', 'mro'] > > ['__class__', '__delattr__', '__doc__', '__getattribute__', > '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', > '__repr__', '__setattr__', '__str__'] > > suggests that type inherits from object since type has all the same > attributes as object plus some additional ones. That seems to > indicate a hierarchy like this: > > object > | > V > type > | > V > Mammals > | > V > Dog > > But then why does issubclass(Dog, type) return False? In your example, Mammal is directly derived from object, and Dog is directly derived from Mammal. Dog isn't derived from type, so it isn't considered a subclass. However, Python does create an instance of class 'type' for each class you define. That doesn't mean that 'type' is a superclass. Try "isinstance(Dog, type)": it will return True. Type does inherit from object, but that's not what you're deriving from. The hierarchy that you're using is: Dog ^ | Mammal ^ | object As you notice, type isn't part of the object hierarchy for Dog. That's why it doesn't show up in the MRO. If you want to make Dog a subclass of type, you'd need to do: >>> class Dog(Mammal, type): ... pass ... >>> issubclass(Dog, type) True I don't know why'd you would want to do that, though. --Jason From wolf_tracks at invalid.com Mon Feb 11 22:21:21 2008 From: wolf_tracks at invalid.com (W. Watson) Date: Mon, 11 Feb 2008 19:21:21 -0800 Subject: Is there a web visitor counter available in Python ... Message-ID: <Me8sj.113$Mh2.58@nlpi069.nbdc.sbc.com> ... that is free for use without advertising that I can use on my web pages? I have no idea is suitable for this. My knowledge of Python is somewhat minimal at this point. Maybe Java is better choice. -- Wayne Watson (Nevada City, CA) Web Page: <speckledwithStars.net> From robin at reportlab.com Fri Feb 22 13:16:23 2008 From: robin at reportlab.com (Robin Becker) Date: Fri, 22 Feb 2008 18:16:23 +0000 Subject: xml escapedness In-Reply-To: <fpn1r7$dq6$1@ger.gmane.org> References: <47BEF58D.2030806@chamonix.reportlab.co.uk> <c1f38650802220825o3820aa86rf9324a03ee5a175c@mail.gmail.com> <47BF0932.4080903@chamonix.reportlab.co.uk> <fpn1r7$dq6$1@ger.gmane.org> Message-ID: <47BF1177.7020206@chamonix.reportlab.co.uk> Steve Holden wrote: > Robin Becker wrote: >> Tim van der Leeuw wrote: >>> On Fri, Feb 22, 2008 at 5:17 PM, Robin Becker <robin at reportlab.com> wrote: >>> >>>> A colleague has decided to keep his django database string values (which >>>> are xml >>>> fragments) in an xml escaped form to avoid having the problem of escaping >>>> them >>>> when they are used in templates etc etc. >>>> >>>> Unfortunately he found that the normal admin doesn't escape on the way >>>> through >>>> so thought of adding a standard mechanism to the save methods. However, >>>> this >>>> brings in the possibility of escaping twice ie once in his original >>>> capture code >>>> and then in the django save methods. >>>> >>> Well -- you escape them in the save() method only when they contain XML >>> charachters like <, > ? How about that, wouldn't that work? >>> >>> --Tim >>> >> ...... >> That might work, but there are all the ampersands etc etc to consider as well. >> So an escaped string could contain &, but so can a raw string. > > by the way, be careful - the Django trunk is already modified to perform > escaping by default, so if your colleague is using 0.96 or older he > should really look at the implications of that change on his design > decision. Storing XML in escaped for is always dodgy, much better to > escape when necessary (and when some other tool isn't doing it for you). > that is, after all, the canonical form. > > regards > Steve I agree wholeheartedly, I would prefer raw in the db. Since we're scraping for some of the content it's hard to eliminate all xml though. -- Robin Becker From steve at holdenweb.com Tue Feb 5 22:47:08 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 05 Feb 2008 22:47:08 -0500 Subject: What is the most simple, quicket, yet most powerful python Web-Framework? In-Reply-To: <f75ec485-22ca-4b79-9408-ce4dc97bc09f@j20g2000hsi.googlegroups.com> References: <5d022604-289d-4d4c-bd9a-286435cf77a6@d21g2000prf.googlegroups.com> <mailman.362.1202268249.9267.python-list@python.org> <f75ec485-22ca-4b79-9408-ce4dc97bc09f@j20g2000hsi.googlegroups.com> Message-ID: <47A92DBC.6000305@holdenweb.com> xkenneth wrote: >> My question is: "What makes you think that there is a royal road to web >> development?" > I don't, I was just hoping there was something I was missing, or more > simple than anything I'd experienced. > >> You have already chosen some technology (Ajax and ZODB) without any >> apparent justification. > I've chosen Ajax for it's asynchronous nature. Alot of the data I'm > going to be displayed needs to be updated immediately as it comes in. > I've chosen ZODB because of the way it operates. I really enjoy the > flexibility of an object-oriented database as well as the ZEO server, > which will allow me to exactly what I need to do. > > Why not just consult your prejudices for the >> others as well. > I haven't made any decisions as to the technology I'm going to use > with prejudice, I simply failed to explain properly why I chose those > technologies. > >> Come to that, why is it even necessary to select a >> Python-based solution? > Most of my codebase is currently in python. I use python to do things > like data acquisiton and signal processing. I'm very familiar with > python, and I enjoy developing in it. Python has the technologies > available to it that allow to do what I want to do. >> I could say "Django can do everything you need from your description of >> your requirements", but then you'd be disappointed that it does in fact >> take time to learn how to do things in Django. Just like it does in any >> other complex framework. > Thanks. From what you've said then you probably *would* get along with Grok, but I am not sure that too much Ajax has been incorporated yet. As far as I know (and it's difficult to track everything webby in Python, there's so much) TurboGears and Pylons (eventually to be integrated, I understand) seem to have gone furthest to integrate Ajax into the framework. You are probably better decoupling the Ajax and the content parts, as most Ajax toolkits are designed to be dropped in to any HTML-based environment. I quite like MochiKit, but that's mostly about overcoming the deficiencies of the JavaScript language. Toolkits like ToscaWidgets will coexist with it quite nicely, and can be used with most web application frameworks. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From musiccomposition at gmail.com Thu Feb 21 20:04:29 2008 From: musiccomposition at gmail.com (Benjamin) Date: Thu, 21 Feb 2008 17:04:29 -0800 (PST) Subject: flattening a dict References: <36e90615-f6fe-4b39-b8a8-eb4d28583a58@j28g2000hsj.googlegroups.com> <09c2d0ff-f5f5-4879-9808-4768f60d6a51@28g2000hsw.googlegroups.com> <mailman.878.1203250770.9267.python-list@python.org> Message-ID: <e1d50552-2e12-4078-a530-6ab8a02609dd@v3g2000hsc.googlegroups.com> On Feb 17, 6:18 am, Terry Jones <te... at jon.es> wrote: > Hi Arnaud & Benjamin > > Here's a version that's a bit more general. It handles keys whose values > are empty dicts (assigning None to the value in the result), and also dict > keys that are not strings (see the test data below). It's also less > recursive as it only calls itself on values that are dicts. > > But.... it returns a dict whose keys are tuples. You then need to decide > what to do with this. Hence the helper function strdictflatten for the case > when all dict keys can be converted to str. > > As I told Arnaud in email, I greatly prefer his version for its elegance. > > Terry > > def dictflatten(d, prefix=None): > result = {} > if prefix is None: prefix = tuple() > for k, v in d.iteritems(): > key = prefix + (k,) > if isinstance(v, dict): > if v: > result.update(dictflatten(v, key)) > else: > result[key] = None > else: > result[key] = v > return result > > def strdictflatten(d, sep='/'): > return dict((sep.join(map(str, k)), v) for k, v in dictflatten(d).iteritems()) Thanks. This is great. Now, how would I restrict the depth of the flattening? For example, what if I just wanted something like this: { "mays" : {"eggs" : "spam"}, "jam" : {"soda" : "soda/love" : "dump"}, lamba" : 23 } They are left alone up the to second level of recursion. > if __name__ == '__main__': > test = { > "" : {}, > 4 : 5, > "mays" : {"eggs" : "spam"}, > "jam" : {"soda" : {"love" : "dump"}}, > "lamba" : 23 > } > > d = dictflatten(test) > print strdictflatten(test) > > >>>> {'': None, 'lamba': 23, 'mays/eggs': 'spam', '4': 5, 'jam/soda/love': 'dump'} From jared.grubb at gmail.com Wed Feb 6 15:46:54 2008 From: jared.grubb at gmail.com (Jared Grubb) Date: Wed, 6 Feb 2008 12:46:54 -0800 Subject: Adding properties to an instance In-Reply-To: <925822270802061243y704da921me72c3cd42fc65be7@mail.gmail.com> References: <925822270802061243y704da921me72c3cd42fc65be7@mail.gmail.com> Message-ID: <925822270802061246g6d05573ey1c16d8f8519fb346@mail.gmail.com> Er, instead of "getattr(self,...) you gotta do "object.__getattr__(self,...)" and same for setattr and delattr. Dumb error on my part. (Otherwise you get infinite recursion!) On Feb 6, 2008 12:43 PM, Jared Grubb <jared.grubb at gmail.com> wrote: > Here's one way of doing what you're asking... I would suggest using > __getattribute__ and __setattr__ to dispatch the methods to the custom class > you invent that holds all those properties. > > For example (I simplified your makeprops into __init__ just to keep the > example short, but you can probably see the idea here..) > > class A(object): > def __init__(self, **kw): > class _PropHolder(object): > pass > for k,v in kw.items(): > setattr(_PropHolder, k, property(fget=itemgetter(k))) > self._custom_props = _PropHolder() > def __getattribute__(self, attr): > try: > return getattr(self._custom_props, attr) > except AttributeError: > return getattr(self, attr) > def __setattr__(self, attr, val): > if hasattr(self._custom_props, attr): > setattr(self._custom_props, attr, val) > else: > setattr(self, attr, val) > def __delattr__(self, attr): > if hasattr(self._custom_props, attr): > delattr(self._custom_props, attr) > else: > delattr(self, attr) > > > > > On 6 Feb 2008, at 12:06, dg.google.groups at thesamovar.net wrote: > > Hi all, > > So I understand that properties belong to a class not an instance, but > nonetheless I want to add properties to an instance. I have a class > which when an instance is created runs some fairly complicated code > and produces a set of names which I'd like to be able to access via > properties. At the moment, I'm using something like obj.getvar(name) > but I'd like to be able to write obj.name. (Note that they can't be > just standard attributes because they only get computed when they are > accessed.) I could generate functions like obj.name() but I want it to > be obj.name instead. > > The solution I've come up with is to create a new class for each > object which is just the real class with some extra properties, and > then dynamically change the class of the object to this new class. > This seems to work, but I wonder if (a) there is a nicer solution than > the one I'll post below, (b) if there are any dangers or pitfalls of > this approach. The obvious difficulty is with derived classes. At the > moment, I'm insisting that a derived class has to call a makeprops() > method to create the properties. > > It's kind of similar to this recipe: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/197965 > > but that recipe has a much simpler situation in which the properties > and values are known at the time of the creation of the object (by > contrast, I don't know what the properties are until the end of the > __init__ method). > > Any thoughts? > > Code below to illustrate my approach. > > import warnings > from operator import itemgetter > > class A(object): > def __init__(self,**kwds): > self._kwds = kwds > self.makeprops() > def __getitem__(self,i): > return self._kwds[i] > def makeprops(self): > if not hasattr(self,'_madeprops'): > self._madeprops = set() > self._failedprops = set() > class _A(self.__class__): > pass > for k,v in self._kwds.items(): > if not k in self._madeprops and k in dir(self): > if not k in self._failedprops: > warnings.warn("Cannot create property "+k+", > already used in object "+str(self),RuntimeWarning) > self._failedprops.add(k) > else: > setattr(_A,k,property(fget=itemgetter(k))) > self._madeprops.add(k) > self.__class__ = _A > > class B(A): > def __init__(self,**kwds): > super(B,self).__init__(**kwds) > self.makeprops() > > class C(A): > def __init__(self,**kwds): > self._kwds = kwds > > a = A(x=1) > b = B(x=2,makeprops=3) > c = C(x=3) > print isinstance(a,A), isinstance(a,B), isinstance(a,C) # True False > False > print isinstance(b,A), isinstance(b,B), isinstance(b,C) # True True > False > print isinstance(c,A), isinstance(c,B), isinstance(c,C) # True False > True > print a.__class__ # <class '__main__._A'> > print b.__class__ # <class '__main__._A'> > print c.__class__ # <class '__main__.C'> > print a.x # 1 > print b.x # 2 > print b.makeprops # <bound method _A.makeprops of <__main__._A object > at 0x00A86810>> > try: > print c.x # raises exception > except AttributeError: > print "c has no element x" > c.makeprops() > print c.x # 3 > print a.__class__ # <class '__main__._A'> > print b.__class__ # <class '__main__._A'> > print c.__class__ # <class '__main__._A'> > > --- > Dan Goodman > http://thesamovar.net/contact > -- > http://mail.python.org/mailman/listinfo/python-list > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080206/3df1a838/attachment.html> From bj_666 at gmx.net Thu Feb 28 15:59:49 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 28 Feb 2008 20:59:49 GMT Subject: Pythons & Ladders References: <75969097-e687-4092-af0d-fd6ce4df2f87@28g2000hsw.googlegroups.com> <3pidnRLtmJ1KulvanZ2dnUVZ_uyinZ2d@comcast.com> <62n52kF23jpgaU1@mid.uni-berlin.de> <V7mdnX79U8QFY1vanZ2dnUVZ_qXinZ2d@comcast.com> Message-ID: <62olm4F23jpgaU4@mid.uni-berlin.de> On Thu, 28 Feb 2008 10:34:45 -0800, Jeff Schwab wrote: >> Hey a flame bait. I'll bite. > > Excuse me? Somebody posts about an introductory course on C++ covering > "dynamic arrays using pointers" and literally says "kill me now," and > I'm the flamer for asking him not to hold the language responsible for > the bad course? > > >> This a bit of an overreaction unless you >> know what the course was about. > > It's supposed to be about C++, according to the OP. Yeah, sorry I've read C. Actually it's about a language called C ++ according to the OP. >> To the OP: If you try C++, don't hold that crappy language against C#, D, >> or Java. ;-) > > What's the relevance of C#, D, or Java to the OP's post? The same as C++ to the OP's post if he would have talked about C. :-) Ciao, Marc 'BlackJack' Rintsch From castironpi at gmail.com Fri Feb 15 21:22:19 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 15 Feb 2008 18:22:19 -0800 (PST) Subject: Solve a Debate References: <cbb35863-5838-4c92-a654-8c73dbea2644@e6g2000prf.googlegroups.com> <47B5C799.2030403@tim.thechases.com> <mailman.824.1203099077.9267.python-list@python.org> <13rbmld9blvup92@corp.supernews.com> Message-ID: <1ecc3e02-3a1f-46fe-9531-c6db1d873615@i29g2000prf.googlegroups.com> On Feb 15, 12:32?pm, Grant Edwards <gra... at visi.com> wrote: > On 2008-02-15, Ivan Van Laningham <ivanl... at gmail.com> wrote: > > > Lookup tables are always significantly faster than a bunch of > > ifs. > > Mostly always. ?It depends on what you mean by "lookup table", > and it depends on how the language implements things. ?If you > by "lookup table" you mean a linearly indexed array, then an > array lookup is O(1), and a series of if/then/elses is O(n). > The indexing operation is going to be faster for all practical > examples I can think of. > > If by "lookup table" you mean an arbitrary mapping (e.g. a > "dict" in Python), then it depends on the hashing/searching > used to implement the lookup operation. It's possible for small > mappings using some types of keys that a series of compares > could be faster than the hashing operation. > > In the general case, if the key being used consists of a lot of > bits, you might have to hash all of the bits before you can > start looking up the result. When doing compares, you can quite > after the first bit doesn't match. ?IOW, you might be able to > do a lot of failed key compares in the time it takes to hash > the key. > > -- > Grant Edwards ? ? ? ? ? ? ? ? ? grante ? ? ? ? ? ? Yow! Can you MAIL a BEAN > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? at ? ? ? ? ? ? ? CAKE? > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?visi.com ? ? ? ? ? ? I forget the name, or it's not on the web. "D-tables"-- sorry, by example: D= [] insert 00101110 D= [ 00101110 ] insert 00101111 D= [ 0010111: [ 0, 1 ] ] insert 1 D= [ [ 0: 010111: [ 0, 1 ] ], 1 ] def insert( x ): for bit in x: if curnode.bit!= bit: addnode( node( curnode, x ) ) return addleaf( x ) Which doesn't do it justice. Anyway, I think it's a log-n lookup on arbitrary data types. How does the Python implementation handle hash collisions? Shoot and pray? From grante at visi.com Sat Feb 9 11:37:18 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 09 Feb 2008 16:37:18 -0000 Subject: OT: Speed of light [was Re: Why not a Python compiler?] References: <28eead2f-a40c-414b-bd3d-a941f8a851a2@d70g2000hsb.googlegroups.com> <7da40f42-f64f-4939-a0dc-d24d1ff85f2d@v4g2000hsf.googlegroups.com> <mailman.382.1202310318.9267.python-list@python.org> <13qjktdbe76da00@corp.supernews.com> <mailman.386.1202314488.9267.python-list@python.org> <13qkhka8rln51c5@corp.supernews.com> <47adb0ca$0$31274$e4fe514c@dreader27.news.xs4all.nl> <mailman.561.1202566486.9267.python-list@python.org> Message-ID: <13qrllu8to5gi52@corp.supernews.com> On 2008-02-09, Thomas Dybdahl Ahle <lobais at gmail.com> wrote: > > On Sat, 2008-02-09 at 14:56 +0100, Martin P. Hellwig wrote: >> > Propagate, travel, what's the difference? >> > >> Unfortunately, I didn't study any of this but I sure do remember the >> answer one drunk physic said to me in a bar when I ask him the question: >> "Does light travel or propagate?" >> He answered: "Depends on how you see light." >> He must have studied philosophy too :-) > > Quantum mechanics are closely related to philosophy. I've never understood that claim. You can philosophize about anything: biology, math, weather, the stars, the moon, and so on. I don't see how QM is any more related to philosophy than any other field in science. -- Grant Edwards grante Yow! RELAX!!... This at is gonna be a HEALING visi.com EXPERIENCE!! Besides, I work for DING DONGS! From steve at REMOVE-THIS-cybersource.com.au Fri Feb 8 07:13:15 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 08 Feb 2008 12:13:15 -0000 Subject: OT: New Hope [was Re: Why not a Python compiler?] References: <28eead2f-a40c-414b-bd3d-a941f8a851a2@d70g2000hsb.googlegroups.com> <7da40f42-f64f-4939-a0dc-d24d1ff85f2d@v4g2000hsf.googlegroups.com> <mailman.382.1202310318.9267.python-list@python.org> <13qjktdbe76da00@corp.supernews.com> <foco94$i4f$1@engnntp2.cig.mot.com> <13qmp56btnr55a4@corp.supernews.com> <87tzkko6dv.fsf@physik.rwth-aachen.de> <mailman.479.1202418471.9267.python-list@python.org> <87ir0zaozf.fsf@physik.rwth-aachen.de> Message-ID: <13qohqr2k2sjf69@corp.supernews.com> On Fri, 08 Feb 2008 08:25:56 +0100, Torsten Bronger wrote: > Hall?chen! > > Reedick, Andrew writes: > >>> -----Original Message----- >>> From: python-list-bounces+jr9445=att.com at python.org [mailto:python- >>> list-bounces+jr9445=att.com at python.org] On Behalf Of Torsten Bronger >>> Sent: Thursday, February 07, 2008 3:32 PM To: python-list at python.org >>> Subject: Re: Why not a Python compiler? >>> >>>> I wonder if George Lucas intended it as a joke or if he thought a >>>> parsec was a unit of time. >>> >>> The latter because it was corrected in the novelization. >> >> Errr... didn't one of the novels explain it away by describing the >> kessel run as a region of space warped by black holes or other objects? >> Bragging rights for crossing such a field thus centered on shortest >> distance instead of time. > > Well, in the link that Grant provided, it says > > In the A New Hope novelization, Han says "standard time units" > rather than "parsecs". Therefore, the reduced distance of Solo's > Kessel Run is most likely a retcon to explain George Lucas's > confusion of time and distance units. Bah humbug! New Hope, new poke. Some of us are old enough to remember when Star Wars was Star Wars: the movie was called Star Wars, the opening credits listed it as Star Wars (with New Hope merely a subtitle specifically to invoke the flavour of the Saturday afternoon movies of Lucas' teen years) and the novelization was called Star Wars. That novel was credited to Lucas but actually ghost-written by Alan Dean Foster. The 1976 Sphere Books edition is called Star Wars, it's subtitled "From the Adventures of Luke Skywalker", and the inside front page refers to the movie as Star Wars. With no subtitle. In that book, Han refers to "twelve standard time parts", a clunky and ugly phrase even stupider than calling it twelve parsecs, which reads and sounds like real language. Personally, I think Lucas should have just said that in that particular galaxy far far away and a long time ago, "parsec" *was* a measure of time. I'd buy that. -- Steven From george.sakkis at gmail.com Tue Feb 19 17:49:00 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 19 Feb 2008 14:49:00 -0800 (PST) Subject: The big shots References: <89d15587-e8de-444c-b240-4a10305146e0@e23g2000prf.googlegroups.com> <fpdj5g$s21$1@panix3.panix.com> <7xmypx61z6.fsf@ruckus.brouhaha.com> <fpdlp7$8vb$1@panix3.panix.com> <ca2ca516-5e17-4945-ab75-623e8b024ea9@n77g2000hse.googlegroups.com> <a5505813-25e6-460d-a586-82d697a1fe2b@41g2000hsc.googlegroups.com> <823e82d6-4faf-453f-9330-a34c262c2f52@e25g2000prg.googlegroups.com> <13rmlqa9hc2344b@corp.supernews.com> Message-ID: <cff198dd-4fe6-402a-b32e-67f4ee97e58b@z70g2000hsb.googlegroups.com> On Feb 19, 5:25?pm, Grant Edwards <gra... at visi.com> wrote: > On 2008-02-19, castiro... at gmail.com <castiro... at gmail.com> wrote: > > Even on my emperical claims, I'm wrong 90% of the time. On > > the subjective ones, I'm not only wrong that much, but no one > > else want to hear, or even can verify them. Smell's fine to > > me. > > > Emotions are prejudiced; and even in my own concrete thoughts, > > I will misidentify myself with another, and others with me. > > When I say "I", I mean "you." > > I've no idea what your point is. I guess you're trying to > explain why your posts appear to be semi-random nonsense? Reminds me of a reply I read in a forum once: "It sounds like English; it even looks like English, but I can't understand a word you're blabbering." > > French and Spanish have impersonal pronouns: "on" and "se", > > respectively. In English, they often come out as, "we", > > "they", and "you" a lot, on occasion a "one", and sometimes, > > even, I. > > Perhaps you need somebody who's fluent in English to help you > proofread your posts? Or help you tune the Eliza program > you're using to generate them? Grant, thanks for the laugh.. this was hilarious :) George From jeff at schwabcenter.com Thu Feb 14 20:24:50 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Thu, 14 Feb 2008 17:24:50 -0800 Subject: RELEASED Python 2.5.2, release candidate 1 In-Reply-To: <43da834e-7a3a-483d-81f0-ac3f3f0a4ffa@u10g2000prn.googlegroups.com> References: <mailman.792.1203024506.9267.python-list@python.org> <87skzv17ot.fsf@benfinney.id.au> <47b4cbe7$0$20024$9b622d9e@news.freenet.de> <43da834e-7a3a-483d-81f0-ac3f3f0a4ffa@u10g2000prn.googlegroups.com> Message-ID: <X4ydnas60NFddCnanZ2dnUVZ_rTinZ2d@comcast.com> Carl Banks wrote: > On Feb 14, 6:16 pm, "Martin v. L?wis" <mar... at v.loewis.de> wrote: >>>> On behalf of the Python development team and the Python community, I'm >>>> happy to announce the release of Python 2.5.2 (release candidate 1). >>> Um. If it's only a release *candidate* of 2.5.2, and not yet a >>> *release* of 2.5.2, could you please announce it as something other >>> than a "release"? >>> It should either be announced as "the release of Python 2.5.2", if >>> that's the case; or "the availability of the Python 2.5.2 release >>> candidate 1". >> Please accept my apologies. I'm not a native speaker, so "to release" >> means to me what the dictionary says it means: m-w's fourth meaning, >> "make available to the public". That's what I did - I made the release >> candidate available to the public. >> >> So is the subject incorrect as well? If so, what should it say? > > > I think it's fine as it is. You can "release" a release candidate. You can, but it's confusing terminology. In the context of software development, a release (PRODUCT_VERSION-RELEASE) is a different beast from a release candidate (PRODUCT_VERSION-RC1). From hniksic at xemacs.org Sat Feb 23 20:10:18 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sun, 24 Feb 2008 02:10:18 +0100 Subject: Article of interest: Python pros/cons for the enterprise References: <e5ae7c80-8bb7-4903-92ff-89e4f62c0239@b29g2000hsa.googlegroups.com> <mailman.1019.1203515892.9267.python-list@python.org> <2f1527a7-2f66-44c7-9665-4d8ff01fa5ab@28g2000hsw.googlegroups.com> <47bd4a24$0$25225$426a74cc@news.free.fr> <f9547b0a-bffa-44b3-8638-12b1dd88fe49@p43g2000hsc.googlegroups.com> <mailman.1057.1203605188.9267.python-list@python.org> <036e93e6-5840-4a3c-8642-67a0a9ec44f2@i7g2000prf.googlegroups.com> <ae0cf9a7-842d-4edf-bd1a-bf4057a694c5@q70g2000hsb.googlegroups.com> <784ec210-f389-4a15-b458-961100de9103@v3g2000hsc.googlegroups.com> <ca9a03a4-ab5e-4e0f-92e4-4982386d7a8e@d5g2000hsc.googlegroups.com> <5MSdncqVGdEXiSPanZ2dnUVZ_vPinZ2d@comcast.com> <d2777845-6684-4a18-9c8a-e4f58e4e6781@q70g2000hsb.googlegroups.com> <AcWdnV4sAZmqwSPanZ2dnUVZ_oSunZ2d@comcast.com> <7xwsoxd00c.fsf@ruckus.brouhaha.com> <f76dnYohFaXb0V3anZ2dnUVZ_u-unZ2d@comcast.com> <mailman.1145.1203814683.9267.python-list@python.org> Message-ID: <8763wfp3b9.fsf@mulj.homelinux.net> "Terry Reedy" <tjreedy at udel.edu> writes: > "Jeff Schwab" <jeff at schwabcenter.com> wrote in message > news:f76dnYohFaXb0V3anZ2dnUVZ_u-unZ2d at comcast.com... > [snip discussion of 'with' statements] > > | Yes, this seems to be the Python way: For each popular feature of some > | other language, create a less flexible Python feature that achieves the > | same effect in the most common cases (e.g. lambda to imitate function > | literals, or recursive assignment to allow x = y = z). > > This is a rather acute observation. Another example is generators versus > full coroutines (or continuations). Another example that comes to mind is "with" statement versus a macro system that allowed one to define custom statements based on try...finally. contextlib.contextmanager implements an even more specific subset of this functionality. From planders at gmail.com Wed Feb 20 11:05:55 2008 From: planders at gmail.com (Preston Landers) Date: Wed, 20 Feb 2008 08:05:55 -0800 (PST) Subject: What's "the standard" for code docs? References: <f977676b-d325-4a9f-b914-fe69a9da05b1@i7g2000prf.googlegroups.com> <e3ca26c3-b34d-467c-b584-5b7ade1a5f53@d5g2000hsc.googlegroups.com> Message-ID: <b5067c87-0809-4881-a7e4-9d968ec5fb85@n58g2000hsf.googlegroups.com> On Feb 20, 2:32 am, Paul McGuire <pt... at austin.rr.com> wrote: > I use epydoc for pyparsing, and I really like the results. Just make > sure that importing your modules doesn't really do anything > substantial (like connect to db's, or run unit tests that run for > hours); epydoc imports your code and then introspects it to extract > the classes, methods, docstrings, etc. OK thanks for the advice. We already have a policy of not doing anything "heavyweight" on module import so in introspection wouldn't be a problem. > (And I think you asked an honest question, and did not deserve the > rude answers you got. This NG is normally better behaved.) Yeah I've been lurking a long time. I've noticed a strange uptick in weirdness lately. No clue why though. From dont at spamon.me Mon Feb 4 14:11:39 2008 From: dont at spamon.me (USCode) Date: Mon, 04 Feb 2008 11:11:39 -0800 Subject: Client side GUI-like web framework ? In-Reply-To: <4f7d69d7-83ef-4492-900b-fdfb36ab48f0@p69g2000hsa.googlegroups.com> References: <iP2dne0yQOTY0jranZ2dnUVZ_hadnZ2d@comcast.com> <4f7d69d7-83ef-4492-900b-fdfb36ab48f0@p69g2000hsa.googlegroups.com> Message-ID: <eY6dnQ1pttXw_jranZ2dnUVZ_rmjnZ2d@comcast.com> riquito at gmail.com wrote: > You just described what XUL aims to be > http://developer.mozilla.org/en/docs/The_Joy_of_XUL > http://developer.mozilla.org/en/docs/XULRunner > > At present it lacks for sure documentation (or maybe it isn't > organized really well) Just took a look at XUL and it in some ways describes what I was thinking except it doesn't appear to deliver it's interface via a browser/web server. Then your application wouldn't be accessible via a web browser through the internet. The XUL application still appears to only execute locally on the client machine? Also, personally I find having to describe your interface directly via XML (XUL) is just plain ugly. From duncan.booth at invalid.invalid Thu Feb 21 08:47:35 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 21 Feb 2008 13:47:35 GMT Subject: Globals or objects? References: <72b59db8-ec9c-480a-9ae7-92a69acb70a6@41g2000hsc.googlegroups.com> Message-ID: <Xns9A4B8C412BA8duncanbooth@127.0.0.1> MartinRinehart at gmail.com wrote: > I had a global variable holding a count. One source Google found > suggested that I wouldn't need the global if I used an object. So I > created a Singleton class that now holds the former global as an > instance attribute. Bye, bye, global. > > But later I thought about it. I cannot see a single advantage to the > object approach. Am I missing something? Or was the original global a > better, cleaner solution to the "I need a value I can read/write from > several places" problem? A singleton is simply another form of global. The benefit of a singleton is that it can be used to encapsulate several related values and methods in a single globally accessible space. The easiest way in Python to implement a singleton is just to use a module: all modules are singletons and there is a defined mechanism (import) for accessing them. It sounds as though you simply replaced a value stored in a singleton object (global in a module) with a value stored in a singleton object (attribute of your class) which is referenced from a singleton object (your module). The real benefit from using an object comes when you stop making it a singleton. Create it at some high level in your code and pass it around as a parameter, or hold a reference to it in some other object which is passed around. When you do this you no longer have a global, and the benefits you get include: * for your counter example, you can have multiple counters counting different things without having to duplicate counter code for each thing you want to count. * it becomes much easier to write tests for your code, because each test can create its own context and be completely independant from the other tests. e.g. you can test a generic counter without having to know you are testing the foo counter or the bar counter, and you can test something which counts foos without having to worry that other tests may already have counted some foos. There is another lesser (and Python specific) benefit to storing a value as an attribute of a class rather than a global in a module: if you later want to intercept assignments to the attribute you can turn it into a property, but doing the same thing on a module is much harder. From JKPeck at gmail.com Fri Feb 1 16:12:52 2008 From: JKPeck at gmail.com (JKPeck) Date: Fri, 1 Feb 2008 13:12:52 -0800 (PST) Subject: Mysterious xml.sax Encoding Exception References: <6edad0b6-1d4a-46ec-a6c2-c8caed3089c3@f47g2000hsd.googlegroups.com> <47A37F89.60308@v.loewis.de> <6aa82d79-99a5-4b33-a3a8-fbb15665f693@f47g2000hsd.googlegroups.com> <47a38657$0$29670$9b622d9e@news.freenet.de> Message-ID: <41c01529-2063-42cd-8552-87da3850b5d0@q39g2000hsf.googlegroups.com> On Feb 1, 1:51 pm, "Martin v. L?wis" <mar... at v.loewis.de> wrote: > > They sent me the actual file, which was created on Windows, as an > > email attachment. They had also sent the actual dataset from which > > the XML was generated so that I could generate it myself using the > > same version of our app as the user has. I did that but did not get > > an exception. > > So are you sure you open the file in binary mode on Windows? > > Regards, > Martin In the real case, the xml never goes through a file but is handed directly to the parser. The api return a Python Unicode string (utf-16). For the file the user sent, if I open it in binary mode, it still has a BOM; otherwise the BOM is removed. But either version works on my system. The basic fact, though, remains, the same code works for me with the same input but not for two particular users (out of hundreds). Regards, Jon From gagsl-py2 at yahoo.com.ar Wed Feb 27 21:03:02 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 28 Feb 2008 00:03:02 -0200 Subject: Making string-formatting smarter by handling generators? References: <47C58E95.1030000@tim.thechases.com> <op.t6681itsx6zn5v@a98gizw.cpe.telecentro.net.ar> <mailman.1370.1204144898.9267.python-list@python.org> <13sc2umh18rgs0d@corp.supernews.com> Message-ID: <op.t67pbck4x6zn5v@gabriel2.softlabbsas.com.ar> En Wed, 27 Feb 2008 23:18:14 -0200, Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> escribi?: > I think there is a good case for % taking an iterator. Here's an > artificial example: > > def spam(): > while True: yield "spam" > > spam = spam() > > "%s eggs tomato and %s" % spam > "%s %s bacon tomato %s and eggs" % spam > "%s %s %s %s %s %s %s %s truffles and %s" % spam > > The iterator could be arbitrarily complex, but the important feature is > that the % operator lazily demands values from it, taking only as few as > it needs. If the iterator is exhausted early, it is an error. The % operator has to know whether you want to convert the iterator itself, or the items yielded. Currently it checks whether its argument is a tuple, and takes its contents. "%s" % "hello" is a (very handy) shortcut for "%s" % ("hello",). Consider the following: py> L = ["hello", "world"] py> print "%s" % L ['hello', 'world'] Your suggestion would make it behave like this: py> print "%s" % L 'hello' Then, if one wants to display the container itself and not the contained items, one should wrap *every* list and every sequence/iterator/iterable object into an one-element tuple. Currently this is only required for tuples. Changing the % operator this way isn't a good idea, but your suggestion could be used in another string method/operator/library function. -- Gabriel Genellina From steve at holdenweb.com Fri Feb 8 19:22:35 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 08 Feb 2008 19:22:35 -0500 Subject: Dear David In-Reply-To: <13qp64ass0c6ga0@corp.supernews.com> References: <d9db3974-5e15-4774-8938-24f8718d25ca@y5g2000hsf.googlegroups.com> <27CC3060AF71DA40A5DC85F7D5B70F38010E3792@AWMAIL04.belcan.com> <mailman.474.1202410120.9267.python-list@python.org> <85624658-1ce7-4ce7-9109-3ac3500c7553@v4g2000hsf.googlegroups.com> <mailman.496.1202429114.9267.python-list@python.org> <0d1f50bc-6d26-4f28-ab63-9ef92df39506@j20g2000hsi.googlegroups.com> <5504f9ac0802071817k31fffd1ey2beb4dbe87ec124d@mail.gmail.com> <fohtrb$kje$1@ger.gmane.org> <mailman.526.1202492894.9267.python-list@python.org> <13qp64ass0c6ga0@corp.supernews.com> Message-ID: <foiro8$tsf$1@ger.gmane.org> Grant Edwards wrote: > On 2008-02-08, Blubaugh, David A. <dblubaugh at belcan.com> wrote: > >> I have discontinued the use of ?????? a long time ago. Why >> is this still a problem? > > You're still top posting and not trimming quotes. That annoys > a lot of people. > It isn't a problem, I was merely replying to Dan Upton. Best forgotten! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From steve at REMOVE-THIS-cybersource.com.au Sat Feb 16 05:17:38 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 16 Feb 2008 10:17:38 -0000 Subject: Floating point bug? References: <b2b884df-b499-4740-9d21-cae87bbd790d@q77g2000hsh.googlegroups.com> <6eba298e-6888-462a-afa7-54fae02c3dce@y5g2000hsf.googlegroups.com> <mailman.758.1202950462.9267.python-list@python.org> <61ibo1F1uqso2U1@mid.uni-berlin.de> <188be6e9-bc05-4a72-924b-1de184980002@n58g2000hsf.googlegroups.com> <rOKdnXO5AucGaynanZ2dnUVZ_tDinZ2d@comcast.com> <9b166b3d-89df-4f26-956a-abbd391167e7@i12g2000prf.googlegroups.com> <13rcd3nskgpv91d@corp.supernews.com> <rYWdnY_f89_koSvanZ2dnUVZ_quhnZ2d@comcast.com> Message-ID: <13rde22ktgpu532@corp.supernews.com> On Fri, 15 Feb 2008 17:30:03 -0800, Jeff Schwab wrote: >> But good advice becomes a superstition when it becomes treated as a >> law: "never test floats for equality". That's simply not true. For >> example, floats are exact for whole numbers, up to the limits of >> overflow. > > That's not true. Epsilon becomes large (in absolute terms) for large > numbers. For 64-bit IEEE floats, eps > 1 at about 10**16. Ah yes, good point. Sorry for my brain-fart, I was conflating integer floats with the comp data type, as used in the Standard Apple Numerics Environment (SANE). It used a floating point data type to store what was effectively a 64-bit integer, which was quite significant in the days when PCs used 16-bit integers! Nevertheless, I stand by my claim, and support it by quoting from Professor W Kahan of Berkley, who wrote in the forward to the Apple Numerics Manual (2nd Edition): [quote] ... because so many computers in the 1960's and 1970's possessed so many different arithmetic anomalies, computational lore has become encumbered with a vast body of superstition purporting to cope with them. One such superstitious rule is "*Never* ask whether floating-point numbers are exactly equal." [end quote] In practice, you often do want to test floating point values within some tolerance. But it isn't a universal law: see also "What Every Computer Scientist Should Know About Floating Point Arithmetic". [quote] Incidentally, some people think that the solution to such anomalies is never to compare floating-point numbers for equality, but instead to consider them equal if they are within some error bound E. This is hardly a cure-all because it raises as many questions as it answers. [end quote] http://docs.sun.com/source/806-3568/ncg_goldberg.html Not directly related to this issue, but to get a great overview of some of the problems with floating point, you could do a lot worse than to read the following interview with Kahan: http://www.ddj.com/184410314 and this wonderful lecture: http://www.cs.berkeley.edu/~wkahan/ieee754status/ieee754.ps where he details how optimizing compilers cause arithmetic errors, how and why the facilities provided by IEEE arithmetic are underused, and finally gives his idea of some things that could be done to turn the situation around. Sadly this lecture was given almost twelve years ago, and things have barely changed. Compilers still do the wrong thing, especially optimizing ones; computations that would be easy with NANs and infinities are needlessly difficult; and benchmarks still over-value speed and under- value getting the right answer, let alone simplicity of programming. >> If you know your floats are whole numbers, and still writing >> something like this: >> >> x = 1234.0 >> y = 1000.0 + 200.0 + 30.0 + 4.0 >> if abs(x-y) < 1e-12: >> print "x and y are equal" >> >> then you are wasting your time and guilty of superstitious behaviour. > > In what way? It's true that you hard-coded integers for which the > margin of error happens to be < 1, No, in this case the error is *precisely* zero. There simply are no rounding errors in this calculation, and the error is zero. If you wrote the test as "if abs(x-y) < 1.0" you'd still be wasting your time. It's true that I gave a hard-coded example, but it is hardly a special case. There are many problem domains that don't require the full range of floats and the type of rounding error you give can't occur. (If your application calculates the amount of concrete needed to build a house, say, then you pretty much know the amounts aren't going to be measured in the trillions of megatonnes. If a user insists on specifying that the house has 1.73e820 stories built on a base measuring 1.82e-87 metres squared, then roundoff is the least of your problems: the algorithms you are applying will no longer be valid.) Or possible you have already rounded the numbers yourself, earlier: >>> x = round(1.5678, 2) >>> x == 1.57 True Why would you do this instead? >>> abs(x - 1.57) < 1e-12 True The important thing is that your numbers have appropriately similar scales. If you know that it going to be the case, then you know that addition won't cause the sort of round-off error. I'm talking about. Naturally there may be other forms of round-off, but rounding error doesn't just appear from nowhere, it is predictable and understandable. -- Steven From josephoswald at gmail.com Tue Feb 5 17:55:20 2008 From: josephoswald at gmail.com (josephoswald+gg@gmail.com) Date: Tue, 5 Feb 2008 14:55:20 -0800 (PST) Subject: Why not a Python compiler? References: <28eead2f-a40c-414b-bd3d-a941f8a851a2@d70g2000hsb.googlegroups.com> <b7e37d49-7974-443f-8a2c-217bd9334ece@v67g2000hse.googlegroups.com> <mailman.337.1202229909.9267.python-list@python.org> <5fcaf0c4-c1b8-425e-82e2-f9136f890a9f@1g2000hsl.googlegroups.com> <13qhmnq9f2vdo2c@corp.supernews.com> Message-ID: <6cc3441a-2a21-4937-ae90-e41d0cb7769b@d21g2000prf.googlegroups.com> On Feb 5, 4:54 pm, Steven D'Aprano <st... at REMOVE-THIS- cybersource.com.au> wrote: > Okay, you know how hard it is to create a software JIT compiler for a > language as dynamic as Python? It's REALLY HARD, which is why it hasn't > already been done[1]. Now you want that done in *hardware*, which is much > harder. Who's going to spend the money on R&D? > To be clear, compiling a language that is dynamic *in the particular way Python is designed to be dynamic*, for example, documenting and exporting as an API the dictionary lookup mechanism for method dispatch, is really hard. Compiling languages such as Lisp, which are quite dynamic, and in some ways much *more* dynamic than Python, to native machine code has been standard practice since the 1970s. The issue is how Python, for whatever reason, was designed as a language. Not with whether it is dynamic or static. From bronger at physik.rwth-aachen.de Thu Feb 14 02:27:35 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Thu, 14 Feb 2008 08:27:35 +0100 Subject: Is there any Generic RSS/ATOM generator in Python? References: <mailman.618.1202741279.9267.python-list@python.org> <slrnfr7pnj.6ad.te_rem_ra_ove_an_forspam@There-Are-Many-Things.consistent.org> Message-ID: <87ve4sc80o.fsf@physik.rwth-aachen.de> Hall?chen! Terran Melconian writes: > On 2008-02-11, js <ebgssth at gmail.com> wrote: > >> Is there any de-fact standard RSS/ATOM generator? (especially, >> I'd like to create Atom's) Do I have to do it myself from >> scratch? > > I looked into similar issues about six months ago. My conclusion > was that generally XML generation libraries (unlike parsers) don't > get written, because there's little enough to them that it isn't > seen as worth doing, and that accepted practice is to just do it > yourself. Maybe I understand you wrongly but there *is* a general XML generator with ElementTree. I wouldn't generate XML directly but using ElementTree to generate Atom. I did it myself three months ago and it was really trivial. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From miller.paul.w at gmail.com Sun Feb 3 14:18:44 2008 From: miller.paul.w at gmail.com (miller.paul.w at gmail.com) Date: Sun, 3 Feb 2008 11:18:44 -0800 (PST) Subject: psyco question References: <2d819b5e-2377-48a3-b1f3-394c1f6f7dda@u10g2000prn.googlegroups.com> <60mgtoF1ro06iU1@mid.uni-berlin.de> Message-ID: <c0ebaec0-1bac-4779-ad0b-f24e749e9303@v29g2000hsf.googlegroups.com> Thanks for your reply. It's been a while since I've used psyco, and it seems either some functions have been added, or I've never needed the other ones. :-) For the record, it looks like psyco.bind (f) f2 = psyco.unproxy(f) would leave me with an optimized f and a function f2 which is the unoptimized version of f. In any case, it looks like I need to RTFM a little more. Thanks Paul From steve at holdenweb.com Sat Feb 16 00:50:27 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 16 Feb 2008 00:50:27 -0500 Subject: Solve a Debate In-Reply-To: <f425fbd0-4b90-4436-9d74-fbeb8701a7a8@h11g2000prf.googlegroups.com> References: <cbb35863-5838-4c92-a654-8c73dbea2644@e6g2000prf.googlegroups.com> <f425fbd0-4b90-4436-9d74-fbeb8701a7a8@h11g2000prf.googlegroups.com> Message-ID: <fp5tj6$h9$1@ger.gmane.org> Dan Bishop wrote: > On Feb 15, 10:24 am, nexes <nexes... at gmail.com> wrote: >> Alright so me and my friend are having argument. >> >> Ok the problem we had been asked a while back, to do a programming >> exercise (in college) >> That would tell you how many days there are in a month given a >> specific month. >> >> Ok I did my like this (just pseudo): >> >> If month = 1 or 3 or etc .... >> noDays = 31 >> Elseif month = 4 or 6 etc .... >> noDays = 30 >> Else >> noDays = 29 >> (we didn't have to take into account a leap year) >> >> He declared an array and assigned the number of days in a month to its >> own element in an array. Now >> I realise that in this example it would not make a difference in terms >> of efficiency, but it is my belief that if >> there is more data that needed to be assigned(i.e. a couple megs of >> data) it would be simpler (and more efficient) to >> do a compare rather then assigning all that data to an array, since >> you are only going to be using 1 value and the rest >> of the data in the array is useless. >> >> What are everyone else's thoughts on this? > > days_in_month = lambda m: m - 2 and 30 + bool(1 << m & 5546) or 28 Elegant, but the 5546 is way too magical for readability. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From stefan_ml at behnel.de Sat Feb 2 01:24:36 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 02 Feb 2008 07:24:36 +0100 Subject: REALLY simple xml reader In-Reply-To: <13q7ioitoam4nbd@corp.supernews.com> References: <BAY114-DAV156E5E89A8CFB83A1DF784BE3B0@phx.gbl> <1090e4100801271040n7bc6b452n346adee02abcd91d@mail.gmail.com> <mailman.1229.1201614825.896.python-list@python.org> <a5fe3dd3-0cbf-4147-8c31-388aedea9fd2@e4g2000hsg.googlegroups.com> <mailman.88.1201775939.9267.python-list@python.org> <60do34F1q1qmlU1@mid.uni-berlin.de> <mailman.93.1201779568.9267.python-list@python.org> <60dsbrF1qj28sU1@mid.uni-berlin.de> <mailman.96.1201783333.9267.python-list@python.org> <87tzkujeq6.fsf@benfinney.id.au> <13q3ri2707niqc6@corp.supernews.com> <47A206D5.8020408@behnel.de> <13q7ioitoam4nbd@corp.supernews.com> Message-ID: <47A40CA4.7080707@behnel.de> Steven D'Aprano wrote: > The same way it knows that "<?xml" is "<?xml" before it sees the > encoding. If the parser knows that the hex bytes > > 3c 3f 78 6d 6c > > (or 3c 00 3f 00 78 00 6d 00 6c 00 if you prefer UTF-16, and feel free to > swap the byte order) > > mean "<?xml" > > then it can equally know that bytes > > 20 09 0a > > are whitespace. According to the XML standard, what else could they be? So, what about all the other unicode whitespace characters? And what about different encodings and byte orders that move the bytes around? Is it ok for a byte stream to start with "00 20" or does it have to start with "20 00"? What about "00 20 00 00" and "00 00 00 20"? Are you sure that means 0x20 encoded in 4 bytes, or is it actually the unicode character 0x2000? What complexity do you want to put into the parser here? "In the face of ambiguity, refuse the temptation to guess" Stefan From dblubaugh at belcan.com Mon Feb 18 17:26:04 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Mon, 18 Feb 2008 17:26:04 -0500 Subject: Question In-Reply-To: <op.t6qoedldx6zn5v@a98gizw.cpe.telecentro.net.ar> References: <27CC3060AF71DA40A5DC85F7D5B70F38010E37C6@AWMAIL04.belcan.com><27CC3060AF71DA40A5DC85F7D5B70F38011854E6@AWMAIL04.belcan.com><86380fd30802181016i4f1a0a22s9edf8cf353117b46@mail.gmail.com><27CC3060AF71DA40A5DC85F7D5B70F38026E5FB8@AWMAIL04.belcan.com> <op.t6qoedldx6zn5v@a98gizw.cpe.telecentro.net.ar> Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F38026E611A@AWMAIL04.belcan.com> I have already solved that problem. Sorry for not alerting you as to me of solving this issue. Thank you very much for the help. I was wondering if you would be interested in helping in the development of a Scipy / MyHDL hybrid. The advantage of this would be to develop FPGA logic with the ease of Python programming. This would especially be helpful in the development of a rapid DSP development system for FPGAS. The rapid speed one could possibly obtain with this system might well be a great deal faster that FPGA development with MATLAB. Thank you for your help. David Blubaugh -----Original Message----- From: Gabriel Genellina [mailto:gagsl-py2 at yahoo.com.ar] Sent: Monday, February 18, 2008 4:24 PM To: python-list at python.org Subject: Re: Question En Mon, 18 Feb 2008 17:48:57 -0200, Blubaugh, David A. <dblubaugh at belcan.com> escribi : > Dan, > I have been working with examples within the Scipy and Numpy framework. > Those are the examples that I have been working with at this time, > including the FFT example. The following command: > python setup.py install. > > Is what I did within the Python IDLE environment. However, python was > not able to see this script file. Under directory should the MyHDL > folder be located?? What I mean by this, should the MyHDL folder be > installed in the same directory as where the Scipy folder is located?? > If I am not making any sense, please inform me as soon as possible. Don't do that from inside IDLE. These are some step by step generic instructions to install a new package; they don't assume much about your previous knowledge. 1) Open a command prompt window (or system prompt, or console, or...). Go to the Start menu, click on Run, type "cmd" (without the quotes), press Enter. 2) See if you can invoke Python directly; type at the command prompt: C:\doesntmatter> python -V (use a capital V, press Enter at the end. Don't type the text at the left of the > sign). You should get a response like this: Python 2.5.1 If you get a similar response (maybe a different Python version), skip to step 5. If you get an error message telling that "python" isn't recognized as a command or something, continue on step 3. 3) Let's try to find where Python is located. As you appear to have IDLE installed and working, open it, and execute these two lines: >>> import sys >>> print sys.executable c:\python25\pythonw.exe Take note of the response, but omit the last "w". We will call this "the full path to python.exe". In the example above, the full path to python.exe would be c:\python25\python.exe 4) Repeat step 2 above, using the full path to python.exe instead of the bare word python: C:\doesntmatter> c:\python25\python.exe -V [press Enter] Python 2.5.1 You should get the installed Python version number, not an error. 5) Decompress the package you want to install into any temporary folder -it doesn't matter where- using your favorite tool (WinRar, WinZip, 7zip, the Zip file handler built into WinXP...). Probably you've already done that. Take note of the temporary folder (should contain the setup.py script) 6) Come back to the command prompt and make that temporary folder your current directory, using the "cd" command. E.g. if it were c:\temp\mypackage-3.2, type: C:\doesntmatter> cd c:\temp\mypackage-3.2 [press Enter] c:\temp\mypackage-3.2> 7) Now execute: c:\temp\mypackage-3.2> python setup.py install [press Enter] (If you had to go thru steps 3 and 4 above, replace the word python with the full path to python.exe) This should start the package installation; read its documentation for further details. -- Gabriel Genellina This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From steve at REMOVE-THIS-cybersource.com.au Sat Feb 9 17:20:42 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 09 Feb 2008 22:20:42 -0000 Subject: different key, same value in dictionaries References: <ee65b681-5af9-42a1-b7ed-799922dece79@l32g2000hse.googlegroups.com> Message-ID: <13qs9pq1v2ude39@corp.supernews.com> On Sat, 09 Feb 2008 13:51:34 -0800, Magdoll wrote: > Is there a cleaner way to do this example: > > d = {('a','b'): 10, ('a','c'): 20, ('b','c'): 30} > > The key is always a pair (x,y), but d[(x,y)] should have the same result > as d[(y,x)]. So either I would have to store both d[(x,y)] and d[(y,x)] > (unncessary extra space?) Worse than the extra space is the near certainty of d[(x,y)] and d[(y,x)] getting out of sync. > or write something like: > > if x <= y: return d[(x,y)] > else: return d[(y,x)] Arggh, scattering all those tests throughout your code is too much like hard work! > I'm not familiar with python enough, so I want to know whether these are > my only choices.... Oh no. Here's a good one: class PairDict(dict): def __getitem__(self, key): if key[1] < key[0]: key = (key[1], key[0]) return super(PairDict, self).__getitem__(key) and here it is in use: >>> d = PairDict([((1,2), 5), ((3,4), 10)]) >>> d[(1,2)] 5 >>> d[(2,1)] 5 -- Steven From pecora at anvil.nrl.navy.mil Sun Feb 24 11:03:51 2008 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Sun, 24 Feb 2008 11:03:51 -0500 Subject: Article of interest: Python pros/cons for the enterprise References: <e5ae7c80-8bb7-4903-92ff-89e4f62c0239@b29g2000hsa.googlegroups.com> <47bd4a24$0$25225$426a74cc@news.free.fr> <f9547b0a-bffa-44b3-8638-12b1dd88fe49@p43g2000hsc.googlegroups.com> <mailman.1057.1203605188.9267.python-list@python.org> <036e93e6-5840-4a3c-8642-67a0a9ec44f2@i7g2000prf.googlegroups.com> <ae0cf9a7-842d-4edf-bd1a-bf4057a694c5@q70g2000hsb.googlegroups.com> <784ec210-f389-4a15-b458-961100de9103@v3g2000hsc.googlegroups.com> <e0b5c8ac-bb35-41a8-a78c-b98ed38add6c@p73g2000hsd.googlegroups.com> <0ca5ddf3-98b6-4f58-93bf-7d0f6576469e@e60g2000hsh.googlegroups.com> <M-6dnaj8Iq2qgiLanZ2dnUVZ_ternZ2d@comcast.com> <691de0bd-a9cc-4e24-8175-89c0863eac9f@u69g2000hse.googlegroups.com> <Y9KdnVYb7bq_m13anZ2dnUVZ_sednZ2d@comcast.com> <mailman.1128.1203771184.9267.python-list@python.org> Message-ID: <pecora-26B779.11035124022008@ra.nrl.navy.mil> Just some anecdotal confirmation: In article <mailman.1128.1203771184.9267.python-list at python.org>, "Ryan Ginstrom" <software at ginstrom.com> wrote: > I personally used C++ for about 90% of my code for 10 years. During that > time, I was chugging the C++ Kool-Aid so hard I almost peed myself. I still > think that C++ is a beautiful language, but I have also come to think that > starting a program with C++ is a premature optimization. Yes, I came to the same conclusion and now start all projects in Python, then add C/C++ extensions for optimization. > I think that very few Python programmers today started with Python. Most of > them came to Python for a reason. Exactly right in my case. In fact this observation is directly related to the one your the previous paragraph. Python is a good language in which to start a progrom. -- -- Lou Pecora From bellman at lysator.liu.se Mon Feb 4 05:49:42 2008 From: bellman at lysator.liu.se (Thomas Bellman) Date: Mon, 4 Feb 2008 10:49:42 +0000 (UTC) Subject: polling for output from a subprocess module References: <48dec8a9-c2da-492c-a639-097fe25fe73c@s8g2000prg.googlegroups.com> Message-ID: <fo6qk6$45r$1@news.lysator.liu.se> jakub.hrozek at gmail.com wrote: > try: > test = Popen(test_path, > stdout=PIPE, > stderr=PIPE, > close_fds=True, > env=test_environ) > while test.poll() == None: > ready = select.select([test.stderr], [], []) > if test.stderr in ready[0]: > t_stderr_new = test.stderr.readlines() > if t_stderr_new != []: > print "STDERR:", "\n".join(t_stderr_new) > t_stderr.extend(t_stderr_new) [...] > The problem is, that it seems that all the output from the subprocess > seems to be coming at once. Do I need to take a different approach? The readlines() method will read until it reaches end of file (or an error occurs), not just what is available at the moment. You can see that for your self by running: $ python -c 'import sys; print sys.stdin.readlines()' The call to sys.stdin.readlines() will not return until you press Ctrl-D (or, I think, Ctrl-Z if you are using MS-Windows). However, the os.read() function will only read what is currently available. Note, though, that os.read() does not do line-based I/O, so depending on the timing you can get incomplete lines, or multiple lines in one read. -- Thomas Bellman, Lysator Computer Club, Link?ping University, Sweden "Adde parvum parvo magnus acervus erit" ! bellman @ lysator.liu.se (From The Mythical Man-Month) ! Make Love -- Nicht Wahr! From jeff at schwabcenter.com Sun Feb 24 00:09:58 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Sat, 23 Feb 2008 21:09:58 -0800 Subject: Article of interest: Python pros/cons for the enterprise In-Reply-To: <7xhcfzdlqc.fsf@ruckus.brouhaha.com> References: <e5ae7c80-8bb7-4903-92ff-89e4f62c0239@b29g2000hsa.googlegroups.com> <2f1527a7-2f66-44c7-9665-4d8ff01fa5ab@28g2000hsw.googlegroups.com> <47bd4a24$0$25225$426a74cc@news.free.fr> <f9547b0a-bffa-44b3-8638-12b1dd88fe49@p43g2000hsc.googlegroups.com> <mailman.1057.1203605188.9267.python-list@python.org> <ae0cf9a7-842d-4edf-bd1a-bf4057a694c5@q70g2000hsb.googlegroups.com> <784ec210-f389-4a15-b458-961100de9103@v3g2000hsc.googlegroups.com> <ca9a03a4-ab5e-4e0f-92e4-4982386d7a8e@d5g2000hsc.googlegroups.com> <5MSdncqVGdEXiSPanZ2dnUVZ_vPinZ2d@comcast.com> <d2777845-6684-4a18-9c8a-e4f58e4e6781@q70g2000hsb.googlegroups.com> <AcWdnV4sAZmqwSPanZ2dnUVZ_oSunZ2d@comcast.com> <7xwsoxd00c.fsf@ruckus.brouhaha.com> <f76dnYohFaXb0V3anZ2dnUVZ_u-unZ2d@comcast.com> <mailman.1145.1203814683.9267.python-list@python.org> <JIudnfqUz6mjR13anZ2dnUVZ_rWtnZ2d@comcast.com> <7xr6f3f3ma.fsf@ruckus.brouhaha.com> <DfednXiRDZffdV3anZ2dnUVZ_vamnZ2d@comcast.com> <7xhcfzdlqc.fsf@ruckus.brouhaha.com> Message-ID: <OKydnaSPoOdiZl3anZ2dnUVZ_uKpnZ2d@comcast.com> Paul Rubin wrote: > Jeff Schwab <jeff at schwabcenter.com> writes: >>> there's actually a published book specifically about C++ pitfalls. >> Mercy, a whole book? > > http://search.barnesandnoble.com/booksearch/isbnInquiry.asp?EAN=9780201179286 > >>> C and C++ should practically be outlawed at this point. >> On what grounds? "I don't approve of the programming language you're >> using. Cease and desist. Nyah!" > > Well, "outlawed" of course is a figure of speech; however use of those > languages should be a red flag in a design review, and a factor in > determining product liability if a program misbehaves. Your product gets the benefit of the doubt if it was written in Python, but not if written in C? What if the Python interpreter screws up? > Think of all > the buffer overflow exploits against Microsoft Windows programs that > couldn't have happened if Microsoft had used safer languages. There > was clearly a failure to use best engineering practices. In the first place, you're not distinguishing C from C++. I know you think they're the same. They're not. Python's array bounds checking is done in C, as is the case for traditional OS kernels. C++, like Python, offers you container types that "smell" like arrays, but do safety checking under the hood; the C++ bounds checks, unlike the Python checks, are done in-language. If C++ were marketed like Java, people might advertise that the C++ standard containers are "pure C++," or that "C++ is written in C++". Secondly, you're going to have a hard time writing an operating system kernel without fixed-size buffers. You have to read data in chunks of some size. It's fine to say that buffer access should be checked to make sure indexes should be in range, but somebody actually has to write the code to do the checking, and then programmers have to use it. Buffer overflows are the result of developers deliberately choosing not to use bounds-checking. In Python, somebody could still define a monolithic array, use different parts of it to represent different things, and then "oops" lose track of their index, thereby overwriting one part of the array with data that should have stayed in the other part. If you're thinking "Yeah, they *could*, but only a dodo would do that, and it's not Python's fault that the programmer did something bone-headed," then you're beginning to get the picture. If you somehow wrote an OS kernel in Python, and the above-mentioned bone-headedness took place, then there would be no "lower level" to save your OS from having a dangerous security hole. Even if the hardware supported checked access for large quantities of arbitrarily sized arrays, somebody would have to enable that access. Even then you're trusting the hardware developers to check for invalid indexes (bus errors and seg faults). Should we outlaw computer hardware, too? Thirdly, you mentioned a "failure to use best engineering practices." If you mean there was a failure to design and implement a bug-free operating system, then by Jiminy, you're right. "Best practices," though, is usually just what managers say when they mean "what everybody else is doing." The idea is that if you're a manager who sticks to "best practices," then if everything goes to hell, the problem can't be linked specifically to you. Server-side Python is now, at this very moment, becoming acceptable as "best practice." It's no better or worse for this; it's just that a lot more uninspired, uncreative programmers are about to start using it. Do not underestimate their ability to make any programming language look bad. If you make it fool-proof, they'll build a better fool. The only way to keep them from writing code that will blow up at run-time is to impose formal verification of their program, every time they change it; that's what the C++ static type system lets you do, in a limited and easily subverted way. Even if you could somehow remove every feature open to potential abuse, and thereby dodo-proof the language, the result would be a slow, weak, ugly language that non-dodos would not want to use. But hey, at least it would still be "best practice." From ericbrunson at gmail.com Thu Feb 7 16:30:52 2008 From: ericbrunson at gmail.com (ericbrunson at gmail.com) Date: Thu, 7 Feb 2008 13:30:52 -0800 (PST) Subject: Setting up a new user and environment from within a python script References: <ee900edd-9b23-4504-9e75-d7782e9e237e@1g2000hsl.googlegroups.com> Message-ID: <f0d46d1a-50d7-4b4b-a37b-df751495d722@m34g2000hsb.googlegroups.com> On Feb 7, 11:15 am, Henry Hollenberg <h... at rcwm.com> wrote: > Hello, > > I have written a script that uses environment variables set during > a particular users login in ".bash_profile" and ".profile". > > I have changed to that users uid and gid in my python script using: > > import os > os.setegid > os.setgid > os.seteuid > os.setuid > > but I still am not picking up the needed environment. When I run: > os.environ I can see that I still have the environment of the user > that owns the python script. > > I would like to maintain the original script owner but somehow pick up > the > correct environment for the targeted user. Several options looked to > create > an environment in a sub-process which I don't think is the correct > solution. > > I could of course cut and paste the values from ".bash_profile" & > ".profile" > but figured there is probably a better, cleaner way to do the same. > > Searched this forum with no luck and checked several python > references. > > What is the best practice to achieve this goal? > > Thanks, Henry Hollenberg Since you're running the python script as root (the only we seteuid would work) you could call the script using "su" and rely on it to set the user's environment: su - otherusername /path/to/your/script Other than that, the alternatives are to parse the user's dot files and set the appropriate env variables from within your script, but that approach is fraught with problems. Hope that helps a little. e. From arnodel at googlemail.com Wed Feb 27 12:33:09 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 27 Feb 2008 09:33:09 -0800 (PST) Subject: Python's BNF References: <85ae78f6-056b-4219-9952-66750e3ebf58@e60g2000hsh.googlegroups.com> Message-ID: <06c14999-f949-4c1d-ad85-3689f2273e2b@d5g2000hsc.googlegroups.com> On Feb 27, 5:23?pm, MartinRineh... at gmail.com wrote: > I spent too long Googling for Python's BNF. Eventually found it at > Python.org, but only by accident. http://www.google.com/search?q=python+grammar -- Arnaud From lists at cheimes.de Tue Feb 5 16:50:36 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 05 Feb 2008 22:50:36 +0100 Subject: IronPython vs CPython: faster in 1.6 times? In-Reply-To: <52c34392-5c5b-49b8-8c75-ba9add438b73@k39g2000hsf.googlegroups.com> References: <52c34392-5c5b-49b8-8c75-ba9add438b73@k39g2000hsf.googlegroups.com> Message-ID: <foalnd$6l0$1@ger.gmane.org> dmitrey wrote: > Hi all, > the url http://torquedev.blogspot.com/2008/02/changes-in-air.html > (blog of a game developers) > says IronPython is faster than CPython in 1.6 times. > Is it really true? > If yes, what are IronPython drawbacks vs CPython? > And is it possible to use IronPython in Linux? IronPython implements only a limited subset of Python. [1] All extension that depend on a C code don't work under IronPython. Christian [1] http://www.codeplex.com/IronPython/Wiki/View.aspx?title=Differences&referringTitle=Home From hniksic at xemacs.org Wed Feb 13 13:15:23 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 13 Feb 2008 19:15:23 +0100 Subject: OT: Speed of light References: <mailman.633.1202748971.9267.python-list@python.org> <W7qdnbVwRuMhWy3anZ2dnUVZ_tCrnZ2d@speakeasy.net> <C42dnQO3-s6BVS3anZ2dnUVZ_o_inZ2d@comcast.com> <6f-dnfwZwvz6Ui3anZ2dnUVZ_oOnnZ2d@speakeasy.net> <QcadnXHHAflcSS3anZ2dnUVZ_hGdnZ2d@comcast.com> <mailman.665.1202803393.9267.python-list@python.org> <ebWdnf1w2af9yyzanZ2dnUVZ_hadnZ2d@speakeasy.net> <13r2p6aivk1no9a@corp.supernews.com> <ENSdnam5yck27CzanZ2dnUVZ_judnZ2d@speakeasy.net> <880dece00802121311n77f73515ve7db8a931825d958@mail.gmail.com> <mailman.706.1202884863.9267.python-list@python.org> <FfKdnR-55_jZsS7anZ2dnUVZ_sKqnZ2d@comcast.com> Message-ID: <87abm4g1tw.fsf@mulj.homelinux.net> Jeff Schwab <jeff at schwabcenter.com> writes: > Jeroen Ruigrok van der Werven wrote: >> -On [20080212 22:15], Dotan Cohen (dotancohen at gmail.com) wrote: >>> Note that Google will give a calculator result for "1 kilogram in >>> pounds", but not for "1 kilogram in inches". I wonder why not? After >>> all, both are conversions of incompatible measurements, ie, they >>> measure different things. >> >> Eh? Last I checked both pound and kilogram are units of mass, so where is >> the incompatibility? > > I've never heard of "pound" as a unit of mass. At least where I went > to school (Boston, MA), "pound" is the English unit of force, "slug" > is the (rarely used) English unit of mass, and "kilogram" is the SI > unit of mass. It would be possible for US pound to only refer to weight, but I cannot find references to corroborate it. For example, taken from Wikipedia: In 1958 the United States and countries of the Commonwealth of Nations agreed upon common definitions for the pound and the yard. The international avoirdupois pound was defined as exactly 453.59237 grams. The "pound-force" wikipedia entry documents "pound" being used as a unit of force "in some contexts, such as structural engineering applications." From darrin_allen at japan.com Sun Feb 3 09:05:51 2008 From: darrin_allen at japan.com (t3chn0n3rd) Date: Sun, 3 Feb 2008 06:05:51 -0800 (PST) Subject: python for game programming Message-ID: <f0c7a0a9-0b3d-4fb6-ac93-3317e404e4de@v17g2000hsa.googlegroups.com> Is Python program language popular for game programming? From andrewm at object-craft.com.au Sun Feb 17 21:25:59 2008 From: andrewm at object-craft.com.au (Andrew McNamara) Date: Mon, 18 Feb 2008 13:25:59 +1100 Subject: CSV module: incorrectly parsed file. In-Reply-To: <4733861b-8128-4cec-9d0b-6543e923a0e3@s13g2000prd.googlegroups.com> References: <4733861b-8128-4cec-9d0b-6543e923a0e3@s13g2000prd.googlegroups.com> Message-ID: <20080218022559.6424F5CCEF0@longblack.object-craft.com.au> >Here is a file "test.csv" >number,name,description,value >1,"wer","tape 2"",5 >1,vvv,"hoohaa",2 > >I want to convert it to tab-separated without those silly quotes. Note >in the second line that a field is 'tape 2"' , ie two inches: there is >a double quote in the string. The input format is ambiguous - how is the parser to distinguish between a double-quote in the field, and the double-quote that delimits the field? Excel would have written that field as "tape 2""" (it doubles double-quotes that appear within a field). You can turn off the double-double-quote handling by passing "doublequote=False" to the parser, but the results still might not be what you want (because the format is ambiguous). -- Andrew McNamara, Senior Developer, Object Craft http://www.object-craft.com.au/ From dikkie at nospam.org Sun Feb 3 10:33:11 2008 From: dikkie at nospam.org (Dikkie Dik) Date: Sun, 03 Feb 2008 16:33:11 +0100 Subject: GUI definition for web and desktop In-Reply-To: <mailman.216.1202010128.9267.python-list@python.org> References: <mailman.216.1202010128.9267.python-list@python.org> Message-ID: <47a5deb8$0$22178$bf4948fe@news.tele2.nl> > .... I have an application > that is accessible through the web and also through desktop > applications and both clients should be presented a simple dialog GUI. > This dialog will only include text fields, radio buttons and a file > upload field. > > My idea is that if there was a lightweight GUI definition format then > I would define the current list of fields and other GUI elements in > this format, expose this file on the web, and both the web client and > the desktop client would first fetch this file and generate the > appropriate GUI from that dynamically. I am very new to Python, and my first python application has a "cascading" user interface: if enough is given on the command-line, it sticks to being a command-line app, and if more data is needed, it presents a GUI. I never did this before, and it taught me a good lesson. The main thing I learned from it is that the GUI tends to control not only the input of the application, but also its flow and modularity structure. I was really glad that I did not include a web interface (which would not have made any sense in my case). The web applications are usually totally different because of: - the stateless nature of HTTP - the use of HTTP headers (session handlers, redirects, authentication) So designing a "local" GUI format that can also be used in a web environment is not really impossible, but hardly practical. For instance, a "local" GUI can hold information, do some validation and store the whole input as a batch, or better said, as a transaction. Web applications do not work this way. Sure, if you rely on javascript (not a good idea if you want your app to be portable), you can do some basic validation and even make server calls. But still, a well-designed web app is more fault tolerant due to the browser variations: In a web environment, you would store "half" inputs that can be finished later, where in local applications you would not. Local GUIs do not suffer from expiring sessions, for example. So a GUI format is not the main problem. The main problem is the "nature" of the whole application. By the way: my User Interface classes did not share a definition file or something. So a simple user interface like yours could easily be generated in two varieties, by two different classes or modules. And a more complex UI would suffer from the difference in nature, so it would even call for two different client applications. Best regards From martin at v.loewis.de Thu Feb 14 18:16:55 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Fri, 15 Feb 2008 00:16:55 +0100 Subject: RELEASED Python 2.5.2, release candidate 1 In-Reply-To: <87skzv17ot.fsf@benfinney.id.au> References: <mailman.792.1203024506.9267.python-list@python.org> <87skzv17ot.fsf@benfinney.id.au> Message-ID: <47b4cbe7$0$20024$9b622d9e@news.freenet.de> >> On behalf of the Python development team and the Python community, I'm >> happy to announce the release of Python 2.5.2 (release candidate 1). > > Um. If it's only a release *candidate* of 2.5.2, and not yet a > *release* of 2.5.2, could you please announce it as something other > than a "release"? > > It should either be announced as "the release of Python 2.5.2", if > that's the case; or "the availability of the Python 2.5.2 release > candidate 1". Please accept my apologies. I'm not a native speaker, so "to release" means to me what the dictionary says it means: m-w's fourth meaning, "make available to the public". That's what I did - I made the release candidate available to the public. So is the subject incorrect as well? If so, what should it say? Regards, Martin From duncan.booth at invalid.invalid Mon Feb 25 11:03:03 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 25 Feb 2008 16:03:03 GMT Subject: Using lambda [was Re: Article of interest: Python pros/cons for theenterprise] References: <e5ae7c80-8bb7-4903-92ff-89e4f62c0239@b29g2000hsa.googlegroups.com> <036e93e6-5840-4a3c-8642-67a0a9ec44f2@i7g2000prf.googlegroups.com> <ae0cf9a7-842d-4edf-bd1a-bf4057a694c5@q70g2000hsb.googlegroups.com> <784ec210-f389-4a15-b458-961100de9103@v3g2000hsc.googlegroups.com> <ca9a03a4-ab5e-4e0f-92e4-4982386d7a8e@d5g2000hsc.googlegroups.com> <5MSdncqVGdEXiSPanZ2dnUVZ_vPinZ2d@comcast.com> <d2777845-6684-4a18-9c8a-e4f58e4e6781@q70g2000hsb.googlegroups.com> <AcWdnV4sAZmqwSPanZ2dnUVZ_oSunZ2d@comcast.com> <7xwsoxd00c.fsf@ruckus.brouhaha.com> <f76dnYohFaXb0V3anZ2dnUVZ_u-unZ2d@comcast.com> <mailman.1145.1203814683.9267.python-list@python.org> <7xmyprtay1.fsf@ruckus.brouhaha.com> <88qdnQR0a7V7Rl3anZ2dnUVZ_rqlnZ2d@comcast.com> <7xmyprf3ef.fsf@ruckus.brouhaha.com> <TOSdnWKX7ZhGeF3anZ2dnUVZ_qiinZ2d@comcast.com> <mailman.1187.1203905598.9267.python-list@python.org> <13s5kclk4maa584@corp.supernews.com> <Xns9A4F9A3AB9E3Cduncanbooth@127.0.0.1> <13s5o11j54pb85b@corp.supernews.com> Message-ID: <Xns9A4FA1DB42C6Fduncanbooth@127.0.0.1> Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> wrote: >> but if >> you pass functions/lambdas around a lot it can be frustrating when you >> get an error such as: >> >> TypeError: <lambda>() takes exactly 2 arguments (1 given) >> >> and the traceback only tells you which line generated the TypeError, not >> which lambda was involved. On the other hand: > > In the simple cases I'm talking about, there is only one lambda in scope > at a time. If that were not the case, I'd use def. > In the fictional example you gave there are potentially two lambdas: the one passed in or the default one. I use lambda quite often myself, but I do feel that if you do have a name for the function then you might as well tell the function what it's called. It probably won't matter, but it doesn't hurt you (2 extra characters to type), and it might just save you grief further down the line. Each to his own though. From namit at namit.org Thu Feb 21 06:32:23 2008 From: namit at namit.org (Christian Kortenhorst) Date: Thu, 21 Feb 2008 11:32:23 +0000 Subject: Backup Script over ssh Message-ID: <c25bf2800802210332s12fe5963od5348f9568e9b964@mail.gmail.com> Hey all I am new to python and the list. I want to create backup script for my windows PC and upload to Linux server over ssh but whats the best way to go about this. Just want to copy the modified and new files up to server in folder that has Month/Year so every month new sync is created, but every day new files at midnight are uploaded. Can anyone help? Thanks -- Christian Kortenhorst -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080221/3deafd46/attachment.html> From bbxx789_05ss at yahoo.com Tue Feb 19 01:54:44 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 18 Feb 2008 22:54:44 -0800 (PST) Subject: usage of <string>.encode('utf-8','xmlcharrefreplace')? References: <a541106e-f098-40aa-b82b-5809bd1883ac@i29g2000prf.googlegroups.com> <mailman.959.1203400359.9267.python-list@python.org> <a332350d-2530-4468-a751-a0d09792396d@q78g2000hsh.googlegroups.com> Message-ID: <c602c7ef-34fa-4cac-b2f5-814feeb15469@n77g2000hse.googlegroups.com> To clarify a couple of points: On Feb 18, 11:38?pm, 7stud <bbxx789_0... at yahoo.com> wrote: >?A unicode string looks like this: > > s = u'\u0041' > > but your string looks like this: > > s = 'he Company\xef\xbf\xbds ticker' > > Note that there is no 'u' in front of your string. ? > That means your string is a regular string. > If a python function requires a unicode string and a unicode string > isn't provided.. For example: encode(). One last point: you can't display a unicode string. The very act of trying to print a unicode string causes it to be converted to a regular string. If you try to display a unicode string without explicitly encode()'ing it first, i.e. converting it to a regular string using a specified secret code--a so called 'codec', python will implicitly attempt to convert the unicode string to a regular string using the default codec, which is usually set to ascii. From http Sun Feb 24 01:21:59 2008 From: http (Paul Rubin) Date: 23 Feb 2008 22:21:59 -0800 Subject: Official IRC channel for Python? References: <mailman.1149.1203827401.9267.python-list@python.org> <7xskzj7yw9.fsf@ruckus.brouhaha.com> <a23effaf0802232116r6f363606tccb10336bd42cc6a@mail.gmail.com> <mailman.1155.1203833401.9267.python-list@python.org> Message-ID: <7xk5ku27so.fsf@ruckus.brouhaha.com> "Manu Hack" <manuhack at gmail.com> writes: > > Really? maybe I'm been blocked from it... > > thanks. > > Maybe you need your nick name to be recognized. You need to register > your nickname somewhere. On freenode, you need to register your nick in order to send private messages, but you can join a channel with an unregistered nick. If the nick is registered to someone else, you get a message saying to identify (which in this situation actually means change nicks, since you presumably don't have the password to identify as the other person). Manu, what happens when you try to join? What happens if you change nicks? Can you connect to freenode at all? Can you join other channels? From darcy at druid.net Thu Feb 28 15:58:31 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Thu, 28 Feb 2008 15:58:31 -0500 Subject: How about adding rational fraction to Python? In-Reply-To: <7xskzcsuad.fsf@ruckus.brouhaha.com> References: <b2b884df-b499-4740-9d21-cae87bbd790d@q77g2000hsh.googlegroups.com> <7xk5kra0p1.fsf@ruckus.brouhaha.com> <fq1ved$6ta$1@rumours.uwaterloo.ca> <7xy797s966.fsf@ruckus.brouhaha.com> <fq224h$7uh$1@rumours.uwaterloo.ca> <b135e0e7-38fd-44f9-a67b-00b69af5ecc6@34g2000hsz.googlegroups.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <c6124f99-247e-4e5b-ab89-884777e25269@v3g2000hsc.googlegroups.com> <7x63wbez2b.fsf@ruckus.brouhaha.com> <13sc3ccds5ap5a9@corp.supernews.com> <13scs8k1kh9nk81@corp.supernews.com> <e44f326c-ccf9-49f3-a2aa-da64e9bfba20@x30g2000hsd.googlegroups.com> <20080228112243.bd752e99.darcy@druid.net> <1204223526.7274.1.camel@aalcdl07.lib.unc.edu> <mailman.1405.1204228689.9267.python-list@python.org> <7xskzcsuad.fsf@ruckus.brouhaha.com> Message-ID: <20080228155831.82a8191e.darcy@druid.net> On 28 Feb 2008 12:25:14 -0800 Paul Rubin <"http://phr.cx"@NOSPAM.invalid> wrote: > "D'Arcy J.M. Cain" <darcy at druid.net> writes: > > > I'd like to point out that now you are talking about int OP int > > > returning a tuple, not an int. > > > > Which would be stupid. Good thing I don't think that "obvious" should > > be the criteria. > > We already have that function (divmod) and it is very useful. Yes it is and has nothing to do with this discussion. I don't think that anyone here has suggested that methods should return the type of their arguments although there have been a few suggestions that the suggestions were made. -- D'Arcy J.M. Cain <darcy at druid.net> | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From toddsalim at gmail.com Tue Feb 12 07:37:09 2008 From: toddsalim at gmail.com (toddsalim at gmail.com) Date: Tue, 12 Feb 2008 04:37:09 -0800 (PST) Subject: hi hi hi its about your life Message-ID: <d02d2081-e3a2-4263-a30d-cdc7f7169fec@y5g2000hsf.googlegroups.com> hi hi hi my name is salim,i am from Morocco i've seen many places of the world on tv screen and few that i've visited either for fun or/and business As you know when we travel we meet a lot of different cultures and people. I found in many pieces i've been to:that people stereotyped islam they prejudge Muslims from what they see in media incidents Allow me to share with you here some information about Jesus Christ in islam, Muslims believe in Jesus Christ (peace and blessingof god be upon Him as one of the mightiest messengers from god, We believe he is born miraculously by the word of god without Father Like Adam Been created without father nor mother. And Marry is his mother the pious,pure female may god be pleased with her A Collection of Debates videos: http://english.truthway.tv All about islam http://www.islam-guide.com/ From root at centis.edu.cu Tue Feb 19 11:29:07 2008 From: root at centis.edu.cu (Erol Robaina Cepero) Date: Tue, 19 Feb 2008 11:29:07 -0500 Subject: python-ldap for plone 3 (python 2.4.4) Message-ID: <200802191129070921.007D5CB6@172.16.1.1> Hi friend!! I need download python-ldap for my plone 3.0.5 that use python 2.4.4. Do you know where I can find it? bye From steve at REMOVE-THIS-cybersource.com.au Mon Feb 18 17:22:50 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 18 Feb 2008 22:22:50 -0000 Subject: flattening a dict References: <36e90615-f6fe-4b39-b8a8-eb4d28583a58@j28g2000hsj.googlegroups.com> <09c2d0ff-f5f5-4879-9808-4768f60d6a51@28g2000hsw.googlegroups.com> <mailman.878.1203250770.9267.python-list@python.org> <28cc2bbf-bb1d-4376-862b-b31fe140e193@v3g2000hsc.googlegroups.com> <d9047111-61d0-4817-88b0-03711e6425cf@62g2000hsn.googlegroups.com> <mailman.881.1203264267.9267.python-list@python.org> <09da5ac7-0b75-4a99-a5ba-d0036ce0cc63@v3g2000hsc.googlegroups.com> <mailman.907.1203342699.9267.python-list@python.org> <Xns9A488EF863387duncanbooth@127.0.0.1> Message-ID: <13rk19qadr4u195@corp.supernews.com> On Mon, 18 Feb 2008 14:03:20 +0000, Duncan Booth wrote: > Why, why, why, why are you using lambda here? It only makes the code > harder to read (and it is bad enough without that). A lambda which is > assigned directly to a variable is a bad code smell. Oh come on. I don't get this allergy to lambda that so many people have. Look at the example given: def flattendict(d) : gen = lambda L : (x for M in exp(L) for x in rec(M)) exp = lambda L : (L+list(kv) for kv in L.pop().iteritems()) rec = lambda M : gen(M) if isinstance(M[-1],dict) else [M] return dict((tuple(L[:-1]),L[-1]) for L in gen([d])) The hard-to-read doesn't come from the lambda (which only adds a keyword and a name to each function), but the algorithm, which combines recursion, generator expressions, and tight coupling between three functions. Would the function be any easier to read written like this? # Untested def flattendict(d): def gen(L): return (x for M in exp(L) for x in rec(M)) def exp(L): return (L+list(kv) for kv in L.pop().iteritems()) def rec(M): return gen(M) if isinstance(M[-1],dict) else [M] return dict((tuple(L[:-1]),L[-1]) for L in gen([d])) No. The function is hard to read, not because it uses lambdas, but because it is obfuscated Python. The lambda syntax doesn't contribute to the obfuscation. And as for your point about bad code smells, no, I don't agree. If your function consists of a single expression, and you don't expect func.__name__ to have a meaningful value, then there's nothing wrong with using a "named lambda". Anonymous functions are first-class objects in Python, just as classes and modules and named functions are, and people shouldn't make up superstitious rules about not assigning them to names. def foo(x): return x+1 foo = lambda x: x+1 The first case uses TWO keywords, a name, a declared argument and an expression; the lambda form uses ONE keyword, a name, a declared argument and an expression. The problem with lambdas comes from people trying to hammer multi- expression functions into a single-expression lambda, hence obfuscating the algorithm. That's no different from people who obfuscate multi- expression functions by writing them as a generator expression. -- Steven From azam.farooq3 at gmail.com Sat Feb 9 04:54:21 2008 From: azam.farooq3 at gmail.com (Farooq) Date: Sat, 9 Feb 2008 01:54:21 -0800 (PST) Subject: Find your location with new GPS EN430A technology Message-ID: <d7669686-8834-4239-a509-d02b62f60570@s13g2000prd.googlegroups.com> www.enmac.com.hk - Natural Voice Guidance - High Resolution Touch Screen - Bluetooth - MP3 & Video Player - Picture Viewer - 2D/3D View - Automatic Reroute - Day/Night Mode - Walking Mode - Add unlimited waypoints - Space to add your own music, pictures, and video - Extensive POI database - Map landforms such as rivers & parks displayed - Support E-book function - AC wall charger - Built-in Li-Ion Battery - Audio output: built-in 2W speaker and earphone jack - Language: English, German, French, Spanish, Dutch, Hungarian, Czechs, Danish, Norwegian, Swedish, Portuguese, Italian, Japanese, Finnish, Romanian, Greek, Russian, Polish - Accessories: Car Charger, Car Stand, USB Charging Cable, Manual, Maps CD (Optional) We do have good prices, for further information please visit our website www.enmac.com.hk From http Fri Feb 15 21:10:40 2008 From: http (Paul Rubin) Date: 15 Feb 2008 18:10:40 -0800 Subject: Turn off ZeroDivisionError? References: <mailman.566.1202594651.9267.python-list@python.org> <63d2e7d1-aa26-4ddc-9d12-42ae636104c1@s37g2000prg.googlegroups.com> <13qunlu5nrva731@corp.supernews.com> <mailman.596.1202679611.9267.python-list@python.org> <13qusltq0v8vt39@corp.supernews.com> <mailman.598.1202682913.9267.python-list@python.org> <13qv4dh7fpe0e93@corp.supernews.com> <da63e980-56de-4499-bdd1-0448875b717e@v46g2000hsv.googlegroups.com> <47b50ed0$0$36357$742ec2ed@news.sonic.net> <46aa8fa7-36d1-4ad1-9ad5-32b32e08338f@e23g2000prf.googlegroups.com> <mailman.826.1203104147.9267.python-list@python.org> <13rcdb39epn024d@corp.supernews.com> <db75a182-48dd-4d85-b638-d5ae68f7b562@u10g2000prn.googlegroups.com> Message-ID: <7xve4pejmn.fsf@ruckus.brouhaha.com> Mark Dickinson <dickinsm at gmail.com> writes: > > But the IEEE standard only supports one of them, aleph(0). > > Technically two: plus and minus aleph(0). > > Not sure that alephs have anything to do with it. They really do not. The extended real line can be modelled in set theory, but the "infinity" in it is not a cardinal as we would normally treat them in set theory. Almost all of what we usually call real analysis can be done in fairly weak subsystems of second order arithmetic, which is a countable theory. There is a fairly interesting rant arguing basically that set theory itself is bogus (not in the sense of being wrong, but in the sense of being unnecessary for most mathematics): http://math.stanford.edu/~feferman/papers/psa1992.pdf From gagsl-py2 at yahoo.com.ar Wed Feb 27 01:16:04 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 27 Feb 2008 04:16:04 -0200 Subject: time.time() strangeness References: <op.t65cskdvz3pzfc@nitrogenycs2> Message-ID: <op.t656c215x6zn5v@gabriel2.softlabbsas.com.ar> En Tue, 26 Feb 2008 17:37:22 -0200, Nitro <nitro at dr-code.org> escribi?: > today I encountered a very odd situation. I am on Windows Vista and using > Python 2.5.2. Here's a code snippet to illustrate my problem: > > # uncomment the next line to trigger the problem > # myExtensionModule.CreateDirect3D9Device() > import time > for i in range(0,100): > print time.time() > > With the line commented time.time() returns a changing value which is > what > I expect. However, when I uncomment it and create a Direct3D9 Device > [1][2] it keeps printing the very same number over and over! I had a similar problem some time ago. When a badly formatted audio file was played (on Windows XP, any player, not from Python), the C function ftime(&x) fails and fills x to all 0's from this moment on. ftime is supposed never to fail, but it does... time.time uses ftime on Windows. A possible workaround (floattime function, in timemodule.c): Change #if defined(HAVE_FTIME) struct timeb t; ftime(&t); return (double)t.time + (double)t.millitm * (double)0.001; #else /* !HAVE_FTIME */ time_t secs; time(&secs); return (double)secs; #endif /* !HAVE_FTIME */ to: time_t secs; #if defined(HAVE_FTIME) double res; struct timeb t; ftime(&t); res = (double)t.time + (double)t.millitm * (double)0.001; if (res>0) return res; #endif /* !HAVE_FTIME */ time(&secs); return (double)secs; (untested, I wrote this right now, but basically it's what I did that time). Finally the Python version was not patched, we just forbid to use that server to play MP3s :) As it was hard to reproduce the problem, I never got to submit a patch. > In my project > I am using twisted which uses time.time() to schedule all calls. Since > time.time() is completely screwed the whole application breaks. > I took a look at [3], but I can't see any obivous way how this all > interacts. Specifically I am not sure which API time.time() uses > internally (timeGetTime maybe?). Knowing this could probably help me > debug > more. See timemodule.c, time.time maps to time_time, which calls floattime, which on Windows uses ftime. > I feel like time.time() should not break (unless the vid card > driver/directx has a major bug). Any idea what might be happening here? > Replacing time.time() with time.clock() in twisted.python.runtime makes > the problem disappear. I guess because it uses QueryPerformanceCounter. Seems like a reasonable patch. -- Gabriel Genellina From steve at holdenweb.com Mon Feb 4 22:42:42 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 04 Feb 2008 22:42:42 -0500 Subject: Very weird behavior in MySQLdb "execute" In-Reply-To: <47A782B1.7010009@animats.com> References: <47a76661$0$36336$742ec2ed@news.sonic.net> <mailman.309.1202157490.9267.python-list@python.org> <47A782B1.7010009@animats.com> Message-ID: <fo8lvg$ohs$1@ger.gmane.org> John Nagle wrote: > Carsten Haese wrote: >> On Mon, 2008-02-04 at 11:30 -0800, John Nagle wrote: >>> Restarting the MySQL instance changes the database. The entry "google.com" >>> disappears, and is replaced by "www.google.com". This must indicate a hanging >>> transaction that wasn't committed. >>> >>> But that transaction didn't come from the Python IDLE session I've been >>> making test calls from. Those queries should match the graphical client >>> exactly. >>> >>> So why don't they agree? >> I don't have a definitive answer, but I do have a piece of generic >> advice. If two database sessions receive differing results, the cause >> could be any of the following factors: >> >> 1) One session is in a transaction, but the other is not. >> >> 2) Both sessions are in a transaction, but they are at different >> isolation levels. >> >> 3) Both sessions are in a transaction, but the transactions were started >> at different times. > > I see what's wrong, I think. I haven't been doing a commit after > a SELECT. I've been careful to commit after write-type actions, > but not after read-only actions. I'm using InnoDB in default mode, > which is REPEATABLE READ, and I've recently switched to long-running > processes which keep the database connection open for hours. So the > data view for a given connection never changes, regardless of what's > happening in other threads. > I believe you are correct in your belief that a commit() is never required after SELECT. Once a database change is committed it should become visible to all other connections (under normal circumstances). regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From rectifier04 at gmail.com Thu Feb 7 11:01:46 2008 From: rectifier04 at gmail.com (Jon "Fluffy" Saul) Date: Thu, 7 Feb 2008 10:01:46 -0600 Subject: print 'hello' -> SyntaxError: invalid syntax In-Reply-To: <3f38aeeb-f12b-411d-ac80-1038d8c524b7@d21g2000prf.googlegroups.com> References: <3f38aeeb-f12b-411d-ac80-1038d8c524b7@d21g2000prf.googlegroups.com> Message-ID: <2691a4aa0802070801p23e6023dxecf811af3bd24048@mail.gmail.com> On Feb 7, 2008 8:52 AM, <ValdezDE at googlemail.com> wrote: > I try to install Python in a Dell D620 with XP PRO version 5.1.2600 > and I am getting this error. I assume that some dlls are missing but I > installed form a fresh python-2.5.1.msi without errors msg. > > Thanks > > Roberto > <snip> > Sounds like a bad install. Try reinstalling, or re-downloading the installer and reinstall. Try both even. -- Push the envelope. Watch it bend. From ricaraoz at gmail.com Sat Feb 23 14:21:38 2008 From: ricaraoz at gmail.com (=?UTF-8?B?UmljYXJkbyBBcsOhb3o=?=) Date: Sat, 23 Feb 2008 16:21:38 -0300 Subject: The big shots In-Reply-To: <880dece00802200237w741649f3u7cb9d616f684b86c@mail.gmail.com> References: <89d15587-e8de-444c-b240-4a10305146e0@e23g2000prf.googlegroups.com> <fpdj5g$s21$1@panix3.panix.com> <7xmypx61z6.fsf@ruckus.brouhaha.com> <fpdlp7$8vb$1@panix3.panix.com> <ca2ca516-5e17-4945-ab75-623e8b024ea9@n77g2000hse.googlegroups.com> <a5505813-25e6-460d-a586-82d697a1fe2b@41g2000hsc.googlegroups.com> <823e82d6-4faf-453f-9330-a34c262c2f52@e25g2000prg.googlegroups.com> <880dece00802200237w741649f3u7cb9d616f684b86c@mail.gmail.com> Message-ID: <47C07242.1090506@bigfoot.com> Dotan Cohen wrote: > On 20/02/2008, castironpi at gmail.com <castironpi at gmail.com> wrote: >> It's a bad sign. If you aren't keeping your thoughts to yourself, and >> thrashing about the world for a peer, a social network, a support >> group, or a community, then you missed the day in grammar school when >> they were handing out smiles. But they're not handing them out >> anymore. > > You talk in analogies. I don't understand them. I do not know Spanish, > and maybe if I knew both Spanish and your local customs, I would > understand your analogies. But as a Hebrew-speaking middle easterner, > I don't. > I am a native Spanish speaker.... and I don't understand him either. It is not cultural. From AWasilenko at gmail.com Tue Feb 19 09:14:14 2008 From: AWasilenko at gmail.com (Adam W.) Date: Tue, 19 Feb 2008 06:14:14 -0800 (PST) Subject: Python seems to be ignoring my except clause... References: <7c1ab99b-844d-43d4-8c54-8a07d223d37c@u72g2000hsf.googlegroups.com> <Xns9A498C90A4844duncanbooth@127.0.0.1> Message-ID: <9b424531-9e95-4971-a642-a7f8e21eb23e@62g2000hsn.googlegroups.com> On Feb 19, 8:49?am, Duncan Booth <duncan.bo... at invalid.invalid> wrote: > The example you posted isn't complete and while I can easily expand it to a > working example it will unfortunately be a working example. > > Try cutting it down yourself to a minimal self-contained example that you > can post. 99% of the time you'll find the problem when you do that and > avoid having to post at all. > > In this case, judging by the stack backtrace quoting the wrong line, I'd > guess you only just added the try..except and for some reason are still > executing the old code without the exception handling.- Hide quoted text - > > - Show quoted text - You hit the nail on the head with the old code, I found it funny myself it was quoting the try statement and not the code within. So I deleted my .pyc files and reran, same thing, but then I closed all open windows and reran it, and it recompiled the pyc and the code "worked". But now there is a new problem. I added a print statement to the except clause to make sure it was executing, and something funny happen, it printed 3 times and then spat this out: File "C:\Users\Adam\Desktop\XMLWorkspace.py", line 72, in parsexml parse(url, FeedHandlerInst) File "C:\Python25\lib\xml\sax\__init__.py", line 33, in parse parser.parse(source) File "C:\Python25\lib\xml\sax\expatreader.py", line 107, in parse xmlreader.IncrementalParser.parse(self, source) File "C:\Python25\lib\xml\sax\xmlreader.py", line 123, in parse self.feed(buffer) File "C:\Python25\lib\xml\sax\expatreader.py", line 211, in feed self._err_handler.fatalError(exc) File "C:\Python25\lib\xml\sax\handler.py", line 38, in fatalError raise exception SAXParseException: http://revision3.com/systm/feed/wmv-large/:78:83: undefined entity Huh? Why did it not raise this BEFORE it attempted to append the string, why did my print statment print 3 times before this error? I think I got past the hump I was hitting, and found a new one, 3 items later, I will investigate. But now I know I have to keep deleting my pyc files or else I will run into trouble. From paul.hermeneutic at gmail.com Tue Feb 19 16:15:27 2008 From: paul.hermeneutic at gmail.com (Paul Watson) Date: Tue, 19 Feb 2008 15:15:27 -0600 Subject: SOAP strategies In-Reply-To: <22442f12-587b-4e8f-98b8-53a08bbe0630@q78g2000hsh.googlegroups.com> References: <1203181157.2649.11.camel@localhost.localdomain> <1203436773.6066.2.camel@localhost.localdomain> <22442f12-587b-4e8f-98b8-53a08bbe0630@q78g2000hsh.googlegroups.com> Message-ID: <1203455727.6911.4.camel@localhost.localdomain> On Tue, 2008-02-19 at 10:01 -0800, Paul Boddie wrote: > On 19 Feb, 16:59, Paul Watson <paul.hermeneu... at gmail.com> wrote: > > > > Have I offended? My apologies if I have. I thought I showed that I had > > done some homework and used Google and did the other things to show that > > I was willing to put forth some effort. Please tell me if I have missed > > something. If I should look somewhere besides Python for doing SOAP, > > then please say that also. Thanks. > > There's a Wiki page here about Web services in Python: > > http://wiki.python.org/moin/WebServices > > I don't think that there's been a great deal of visible activity > around SOAP in the Python community other than that you've already > noticed. I entertained the idea of doing some more complete SOAP > support as an add-on to the libxml2dom project, but not wanting to > implement all the related specifications (schemas, service > descriptions), I struggle to see the benefit compared to simpler > solutions. > > That's not to say that SOAP has no value. Clearly, if you consider the > different "use cases", SOAP is probably more appropriate for some than > other solutions would be. If one were exposing some kind of repository > through some kind of Web service, I'd consider approaches like REST, > along with technologies like WebDAV (which overlaps with REST), XML- > RPC and SOAP. But if the Web service were to involve issuing > relatively complicated queries, and/or the repository wasn't strictly > hierarchical (or couldn't be elegantly represented in such a way), > then it would arguably be less appropriate to deploy a "pure" REST > solution, favouring XML-RPC and SOAP instead. > > What undermines SOAP for me is that if I'm not too interested in > treating it like some kind of RPC mechanism, then I can get most of > the pertinent benefits from exchanging plain XML documents. You can, > of course, do SOAP like this, but the obligation to look after the > boilerplate elements (which should permit lots of fancy features like > "routing", if such stuff is actually used in the real world) seems > like a distraction to me. > > Paul Many thanks for your comments. I will take a look at the site. My primary orientation is in accessing large (one or more terabyte) databases and doing data integration (ETL, ELT, EAI, EII) work. Any other suggestions? From jeff at schwabcenter.com Fri Feb 22 14:15:41 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Fri, 22 Feb 2008 11:15:41 -0800 Subject: Article of interest: Python pros/cons for the enterprise In-Reply-To: <0ca5ddf3-98b6-4f58-93bf-7d0f6576469e@e60g2000hsh.googlegroups.com> References: <e5ae7c80-8bb7-4903-92ff-89e4f62c0239@b29g2000hsa.googlegroups.com><mailman.1019.1203515892.9267.python-list@python.org><2f1527a7-2f66-44c7-9665-4d8ff01fa5ab@28g2000hsw.googlegroups.com><47bd4a24$0$25225$426a74cc@news.free.fr> <f9547b0a-bffa-44b3-8638-12b1dd88fe49@p43g2000hsc.googlegroups.com> <mailman.1057.1203605188.9267.python-list@python.org> <036e93e6-5840-4a3c-8642-67a0a9ec44f2@i7g2000prf.googlegroups.com> <ae0cf9a7-842d-4edf-bd1a-bf4057a694c5@q70g2000hsb.googlegroups.com> <784ec210-f389-4a15-b458-961100de9103@v3g2000hsc.googlegroups.com> <e0b5c8ac-bb35-41a8-a78c-b98ed38add6c@p73g2000hsd.googlegroups.com> <0ca5ddf3-98b6-4f58-93bf-7d0f6576469e@e60g2000hsh.googlegroups.com> Message-ID: <M-6dnaj8Iq2qgiLanZ2dnUVZ_ternZ2d@comcast.com> Nicola Musatti wrote: > The real sad thing is that nobody is likely to convince Guido to turn > CPython into C++Python ;-) How difficult would that be? Could it be done in stages? I would be willing to spend some time on that kind of project. Since I know almost nothing about Python internals, though, I'd appreciate it if a C++-fluent Python expert could give an estimate in person-months. Also, what would be the general break-down? Maybe: (1) Prepare a build environment appropriate for Python, supporting code in both C and C++. Include unit-test targets, and a mechanism for module developers to add unit tests to those targets. (2) Get all the headers C++-clean. (3) Begin translating one module at a time. Different people could work on different modules, and add their test-cases to the global target. One potential problem would be linkage. Would Python-internal C++ modules still have to provide C-linkable APIs, so that they could be invoked from other parts of Python? A breakdown of module dependencies would help address this issue, so that it would be clear which parts of the code-base would be directly affected by translating a given module to C++. At the external API level, would it still be important to support C-style linkage, even if the implementation code isn't written in C? I don't know whether it's realistic for people embedding Python in non-C++ applications to have to work directly with C++ APIs. From miki.tebeka at gmail.com Thu Feb 21 17:54:21 2008 From: miki.tebeka at gmail.com (Miki) Date: Thu, 21 Feb 2008 14:54:21 -0800 (PST) Subject: Tkinter OSX and "lift" References: <be6a4620-8b8c-432c-8990-2be7fd43b070@h11g2000prf.googlegroups.com> <47BD7D5F.1060205@codebykevin.com> <29454149-0dfa-4092-a625-0955dbc6ca5d@e10g2000prf.googlegroups.com> <47BD9E6A.2090607@codebykevin.com> Message-ID: <ce73482c-de3a-40e7-8e07-4aad49c4f1a8@u69g2000hse.googlegroups.com> Hello Kevin, > "Lift" (which calls the Tk command "raise") doesn't work this way, at > least not under Aqua. If your application has focus, "lift" will raise > the widget being called to the top of the stacking order. However, it > will not make the application frontmost. To do this you'd have to use > Carbon calls (look at Carbon.CarbonEvt) or use a Tk extension and call > it from Python. Of course, this is pretty much a non-issue if your > application is wrapped as a standard Mac application bundle via > py2app--most Mac users don't run Python apps from the Terminal but > instead double-click an application icon. In that event, "lift" should > work fine, because the application will already have focus. Thanks, -- Miki <miki.tebeka at gmail.com> http://pythonwise.blogspot.com From arnodel at googlemail.com Sun Feb 3 04:05:24 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 3 Feb 2008 01:05:24 -0800 (PST) Subject: bags? 2.5.x? References: <j9Nij.7468$se5.1193@nlpi069.nbdc.sbc.com> <mailman.951.1201074920.896.python-list@python.org> <QHMoj.9940$EZ3.1567@nlpi070.nbdc.sbc.com> <7xtzkscnu0.fsf@ruckus.brouhaha.com> <cb2bc32e-4492-480f-85f1-3464ce4e1d23@s8g2000prg.googlegroups.com> <7xfxwbpvip.fsf@ruckus.brouhaha.com> <c64364a2-358e-4206-996e-659e308bdf3d@h11g2000prf.googlegroups.com> Message-ID: <f873afa0-be96-487e-a33f-10b067d8251a@z17g2000hsg.googlegroups.com> On Feb 2, 3:21?pm, MRAB <goo... at mrabarnett.plus.com> wrote: > I could see uses for both types of union. You could have both A + B > which adds the multiplicities (the smallest bag which contains both > the bags) and A | B which takes the max of the multiplicities (the > smallest bag which contains either of the bags). I agree, and this is what I proposed in my post (except that I spelt A| B as A.union(B)) -- Arnaud From kay.schluehr at gmx.net Tue Feb 5 14:04:17 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Tue, 5 Feb 2008 11:04:17 -0800 (PST) Subject: Project naming suggestions? References: <b99252ef-418c-4954-ae2a-d43f1f008c86@h11g2000prf.googlegroups.com> <mailman.330.1202218870.9267.python-list@python.org> Message-ID: <9df97778-5e67-43ae-a468-e441112f6db1@c23g2000hsa.googlegroups.com> On 5 Feb., 14:41, "Neil Cerutti" <mr.ceru... at gmail.com> wrote: > On Feb 3, 2008 1:17 PM, <miller.pau... at gmail.com> wrote: > > > > > I'm considering writing a little interpreter for a python-like > > language and I'm looking for name suggestions. :-) > > > Basically, I don't want to change a whole lot about Python. In fact, > > I see myself starting with the compiler module from Python 2.5 and > > building from there. > > > This language would be more or less "Python modulo a few > > (incompatible) changes, but it'd be recognizable by Python > > programmers. I'm talking about stuff like "allowing the character '?' > > in identifier names," and "a better way to express 'for dummy in > > xrange (n):' when the index isn't needed." I'd also like to > > implement most of the planned Python 3000 changes. > > > Any suggestions? I'm thinking "Ophidian," for the snake connection, > > or, possibly, "Circus," from "Monty Python's Flying Circus." > > Given your stated goals, I like "Phyton." I hear the masses chanting: "Long live Phyton, down with Python!" "More radical than Larry Wall!" > > -- > Neil Cerutti <mr.cerutti+pyt... at gmail.com> From ebgssth at gmail.com Wed Feb 27 07:39:06 2008 From: ebgssth at gmail.com (js) Date: Wed, 27 Feb 2008 21:39:06 +0900 Subject: Official IRC channel for Python? In-Reply-To: <87y79altyx.fsf@rudin.co.uk> References: <mailman.1149.1203827401.9267.python-list@python.org> <7xskzj7yw9.fsf@ruckus.brouhaha.com> <a23effaf0802232116r6f363606tccb10336bd42cc6a@mail.gmail.com> <mailman.1155.1203833401.9267.python-list@python.org> <7xk5ku27so.fsf@ruckus.brouhaha.com> <87y79altyx.fsf@rudin.co.uk> Message-ID: <a23effaf0802270439k73ce967cs439afec4164baafb@mail.gmail.com> > You can't join #python on freenode without identifying with nickserv > first. Why is that? I can join #perl, #php, #ruby, #mysql, #postgres without registration. What advantage does it have? and the advantage really worth? If #python were the developer's room, I'd say it's reasonable, but that's not the case here. From te_rem_ra_ove_an_forspam at consistent.org Thu Feb 14 02:00:03 2008 From: te_rem_ra_ove_an_forspam at consistent.org (Terran Melconian) Date: Thu, 14 Feb 2008 01:00:03 -0600 Subject: Is there any Generic RSS/ATOM generator in Python? References: <mailman.618.1202741279.9267.python-list@python.org> Message-ID: <slrnfr7pnj.6ad.te_rem_ra_ove_an_forspam@There-Are-Many-Things.consistent.org> On 2008-02-11, js <ebgssth at gmail.com> wrote: > Is there any de-fact standard RSS/ATOM generator? (especially, I'd > like to create Atom's) > Do I have to do it myself from scratch? I looked into similar issues about six months ago. My conclusion was that generally XML generation libraries (unlike parsers) don't get written, because there's little enough to them that it isn't seen as worth doing, and that accepted practice is to just do it yourself. From sjmachin at lexicon.net Sat Feb 16 16:43:37 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 16 Feb 2008 13:43:37 -0800 (PST) Subject: Solve a Debate References: <cbb35863-5838-4c92-a654-8c73dbea2644@e6g2000prf.googlegroups.com> <f425fbd0-4b90-4436-9d74-fbeb8701a7a8@h11g2000prf.googlegroups.com> Message-ID: <921723f8-bfc6-4339-85b7-dae17bc2f894@i29g2000prf.googlegroups.com> On Feb 16, 3:48 pm, Dan Bishop <danb... at yahoo.com> wrote: > On Feb 15, 10:24 am, nexes <nexes... at gmail.com> wrote: > > > > > Alright so me and my friend are having argument. > > > Ok the problem we had been asked a while back, to do a programming > > exercise (in college) > > That would tell you how many days there are in a month given a > > specific month. > > > Ok I did my like this (just pseudo): > > > If month = 1 or 3 or etc .... > > noDays = 31 > > Elseif month = 4 or 6 etc .... > > noDays = 30 > > Else > > noDays = 29 > > (we didn't have to take into account a leap year) > > > He declared an array and assigned the number of days in a month to its > > own element in an array. Now > > I realise that in this example it would not make a difference in terms > > of efficiency, but it is my belief that if > > there is more data that needed to be assigned(i.e. a couple megs of > > data) it would be simpler (and more efficient) to > > do a compare rather then assigning all that data to an array, since > > you are only going to be using 1 value and the rest > > of the data in the array is useless. > > > What are everyone else's thoughts on this? > > days_in_month = lambda m: m - 2 and 30 + bool(1 << m & 5546) or 28 Alternatively: days_in_month = lambda m: m - 2 and 31 - ((m + 9) % 12 % 5 % 2) or 28 the guts of which is slightly more elegant than the ancient writing from which it was derived: MOD(MOD(MOD(M+9,12),5),2) From pavlovevidence at gmail.com Mon Feb 18 01:25:36 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 17 Feb 2008 22:25:36 -0800 (PST) Subject: How about adding rational fraction to Python? References: <b2b884df-b499-4740-9d21-cae87bbd790d@q77g2000hsh.googlegroups.com> <13rcd3nskgpv91d@corp.supernews.com> <rYWdnY_f89_koSvanZ2dnUVZ_quhnZ2d@comcast.com> <13rde22ktgpu532@corp.supernews.com> <26641b5f-d6cb-45a6-8736-7d130d1a5aee@u10g2000prn.googlegroups.com> <13a4316e-3ce7-4b3e-b418-6efb988a8845@q78g2000hsh.googlegroups.com> <676ca28c-b471-41c8-8661-fcd2ea8c23f0@i12g2000prf.googlegroups.com> <74b95b3b-1d6a-42a6-b55d-e77a868b1ffe@64g2000hsw.googlegroups.com> <K_adnYlVJrhd9SranZ2dnUVZ_iydnZ2d@comcast.com> <dde6d718-fb7d-4bce-a1da-5e78c744cf69@72g2000hsu.googlegroups.com> <naidnRHl24M8GCranZ2dnUVZ_vHinZ2d@comcast.com> <70ecaf16-7308-455f-9048-730b2b2f9f2f@p43g2000hsc.googlegroups.com> <13rf9tvbkt66r2a@corp.supernews.com> <198927a7-9478-42b3-a972-82049f0130ac@u10g2000prn.googlegroups.com> Message-ID: <1bc9bba7-dc7f-4cfe-8e1c-fa5901c9f556@n77g2000hse.googlegroups.com> On Feb 17, 1:45 pm, Lie <Lie.1... at gmail.com> wrote: > > Any iteration with repeated divisions and additions can thus run the > > denominators up. This sort of calculation is pretty common (examples: > > compound interest, numerical integration). > > Wrong. Addition and subtraction would only grow the denominator up to > a certain limit I said repeated additions and divisions. Anyways, addition and subtraction can increase the denominator a lot if for some reason you are inputing numbers with many different denominators. Carl Banks From arnodel at googlemail.com Fri Feb 1 14:07:09 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 1 Feb 2008 11:07:09 -0800 (PST) Subject: How to identify which numbers in a list are within each others' range References: <6b4ac79b-6267-438d-8b28-aa4bba78a586@i3g2000hsf.googlegroups.com> <1ffed8a2-f00b-4913-802f-b2cc9fa0ab19@i12g2000prf.googlegroups.com> <mailman.149.1201864990.9267.python-list@python.org> <073ebb96-3572-4aa5-88d6-53e97cc55633@c4g2000hsg.googlegroups.com> Message-ID: <8929bd09-4302-4008-92ed-e072b804e062@q77g2000hsh.googlegroups.com> On Feb 1, 1:28?pm, Arnaud Delobelle <arno... at googlemail.com> wrote: > Yours ?is O(n^2) and \Omega(n^2). ?I think mine is O(max(c, nlogn)) > (assuming constant time access for dictionaries, but 'inside' could be > replaced with a list) where c is the number of overlaps. ?I'll try to > post a proof later (if it's true!). ?So if we are in a situation where > overlaps are rare, it is in practice O(nlogn). I have slightly modified overlaps() in order to make the analysis easier (I have made overlaps() consider all intervals open). Here is the new version: def open_interval(i, (a, b)): return (a, 1, i), (b, 0, i) def overlaps(lst, interval=open_interval): bounds = chain(*starmap(interval, enumerate(lst))) # 1 inside = {} # 2 for x, _, i in sorted(bounds): # 3 if inside.pop(i, None) is None: # 4 for j, y in inside.iteritems(): yield i, j # 5 inside[i] = x # 6 'Detailed' analysis of running overlaps(lst) follows, where * lst is of length n * the total number of overlaps in m (assuming dict.__getitem__ and dic.__setitem__ are done in constant time [1]) 1. is a simple loop over lst, takes An 2. is constant (K) 3. The sorted(...) function will take Bnlogn 3,4. This loop is iterated 2n times, with the if condition it will take Cn 5. This loop is iterated once for each overlap exacly. So it will take Dm 6. This statement is executed n times, will take En Altogether the time taken is: K + (A+B+E)n + Bnlogn + Dm So if m is dominated by nlogn, the algorithm is O(nlogn). Otherwise one cannot hope for better thant O(m)! -- Arnaud [1] Otherwise one could use a combination of an array and a doubly linked list to achieve constant time access, deletion and updating of the 'inside' structure. Anyway even if it was log(n) the overall complexity would be the same! From ebugbee at gmail.com Sun Feb 10 03:42:50 2008 From: ebugbee at gmail.com (ThunderBug) Date: Sun, 10 Feb 2008 00:42:50 -0800 (PST) Subject: Pure Python Salsa20 Stream Cipher Implementation References: <6ddc44aa-7c71-4cee-a6db-31dac0402bd6@z17g2000hsg.googlegroups.com> <7xir0zvm7g.fsf@ruckus.brouhaha.com> Message-ID: <6c7eecd3-4b1b-418a-8209-138d9062c7f0@s8g2000prg.googlegroups.com> And FWIW.... there already exists a pySalsa20, a ctypes wrapper for Bernstein's eSTREAM submission. http://www.seanet.com/~bugbee/crypto/ From jeff at schwabcenter.com Sat Feb 2 22:48:28 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Sat, 02 Feb 2008 19:48:28 -0800 Subject: Does anyone else use this little idiom? In-Reply-To: <e82b13fe-0974-400f-ac5b-0583a86fd9e0@q39g2000hsf.googlegroups.com> References: <e82b13fe-0974-400f-ac5b-0583a86fd9e0@q39g2000hsf.googlegroups.com> Message-ID: <G_ednUF6dcbipDjanZ2dnUVZ_u-unZ2d@comcast.com> How miller.paul.w at gmail.com wrote: > Ruby has a neat little convenience when writing loops where you don't > care about the loop index: you just do n.times do { ... some > code ... } where n is an integer representing how many times you want > to execute "some code." > > In Python, the direct translation of this is a for loop. When the > index doesn't matter to me, I tend to write it as: > > for _ in xrange (1,n): > some code > > An alternative way of indicating that you don't care about the loop > index would be > > for dummy in xrange (1,n): > some code > > But I like using _ because it's only 1 character and communicates well > the idea "I don't care about this variable." > > The only potential disadvantages I can see are threefold: > > 1. It might be a little jarring to people not used to it. I do admit > it looks pretty strange at first. > > 2. The variable _ has special meaning at the interactive interpreter > prompt. There may be some confusion because of this. > > 5. Five is right out. (ob Holy Grail reference, of course. :-) > > So, I guess I'm wondering if anyone else uses a similar idiom and if > there are any downsides to it that I'm not aw Would something like this be acceptable? It still requires a loop variable, plus an extra line of code per loop, plus a one-time class definition (and import into each client module), and it's probably slower than "for dummy in range." The syntax might be more inuitive than "dummy" or "_" in a for loop, though. class Go: def __init__(self, count): self.count = count def again(self): if self.count <= 0: return False self.count -= 1 return True go = Go(3) while go.again(): print "hello" From robin at reportlab.com Fri Feb 22 12:41:06 2008 From: robin at reportlab.com (Robin Becker) Date: Fri, 22 Feb 2008 17:41:06 +0000 Subject: xml escapedness In-Reply-To: <c1f38650802220825o3820aa86rf9324a03ee5a175c@mail.gmail.com> References: <47BEF58D.2030806@chamonix.reportlab.co.uk> <c1f38650802220825o3820aa86rf9324a03ee5a175c@mail.gmail.com> Message-ID: <47BF0932.4080903@chamonix.reportlab.co.uk> Tim van der Leeuw wrote: > On Fri, Feb 22, 2008 at 5:17 PM, Robin Becker <robin at reportlab.com> wrote: > >> A colleague has decided to keep his django database string values (which >> are xml >> fragments) in an xml escaped form to avoid having the problem of escaping >> them >> when they are used in templates etc etc. >> >> Unfortunately he found that the normal admin doesn't escape on the way >> through >> so thought of adding a standard mechanism to the save methods. However, >> this >> brings in the possibility of escaping twice ie once in his original >> capture code >> and then in the django save methods. >> > > Well -- you escape them in the save() method only when they contain XML > charachters like <, > ? How about that, wouldn't that work? > > --Tim > ...... That might work, but there are all the ampersands etc etc to consider as well. So an escaped string could contain &, but so can a raw string. -- Robin Becker From odysseus1479-at at yahoo-dot.ca Mon Feb 4 07:25:24 2008 From: odysseus1479-at at yahoo-dot.ca (Odysseus) Date: Mon, 04 Feb 2008 12:25:24 GMT Subject: Elementary string-parsing References: <odysseus1479-at-9C5D4F.20211803022008@news.telus.net> <13qd6ec9vv1qv9a@corp.supernews.com> Message-ID: <odysseus1479-at-911721.05252304022008@news.telus.net> In article <13qd6ec9vv1qv9a at corp.supernews.com>, Dennis Lee Bieber <wlfraed at ix.netcom.com> wrote: <snip> > Rather complicated description... A sample of the real/actual input > /file/ would be useful. Sorry, I didn't want to go on too long about the background, but I guess more context would have helped. The data actually come from a web page; I use a class based on SGMLParser to do the initial collection. The items in the "names" list were originally "title" attributes of anchor tags and are obtained with a "start_a" method, while "cells" holds the contents of the <td> tags, obtained by a "handle_data" method according to the state of a flag that's set to True by a "start_td" method and to False by an "end_td". I don't care about anything else on the page, so I didn't define most of the tag-specific methods available. <snip> > cellRoot = 10 * i + na #where did na come from? > #heck, where do names and cells > #come from? Globals? Not recommended.. The variable "na" is the number of 'not applicable' items (headings and whatnot) preceding the data I'm interested in. I'm not clear on what makes an object global, other than appearing as an operand of a "global" statement, which I don't use anywhere. But "na" is assigned its value in the program body, not within any function: does that make it global? Why is this not recommended? If I wrap the assignment in a function, making "na" a local variable, how can "extract_data" then access it? The lists of data are attributes (?) of my SGMLParser class; in my misguided attempt to pare irrelevant details from "extract_data" I obfuscated this aspect. I have a "parse_page(url)" function that returns an instance of the class, as "captured", and the lists in question are actually called "captured.names" and "captured.cells". The "parse_page(url)" function is called in the program body; does that make its output global as well? > use > > def extract_data(names, na, cells): > > and > > return <something> What should it return? A Boolean indicating success or failure? All the data I want should all have been stored in the "found" dictionary by the time the function finishes traversing the list of names. > > for k in ('time', 'score1', 'score2'): > > v = found[name][k] > > if v != "---" and v != "n/a": # skip non-numeric data > > v = ''.join(v.split(",")) # remove commas between 000s > > found[name][k] = float(v) > > I'd suggest splitting this into a short function, and invoking it in > the preceding... say it is called "parsed" > > "time" : parsed(cells[cellRoot + 5]), Will do. I guess part of my problem is that being unsure of myself I'm reluctant to attempt too much in a single complex statement, finding it easier to take small and simple (but inefficient) steps. I'll have to learn to consolidate things as I go. > Did you check the library for time/date parsing/formatting > operations? > > >>> import time > >>> aTime = "03 Feb 2008 20:35:46 UTC" #DD Mth YYYY HH:MM:SS UTC > >>> time.strptime(aTime, "%d %b %Y %H:%M:%S %Z") > (2008, 2, 3, 20, 35, 46, 6, 34, 0) I looked at the documentation for the "time" module, including "strptime", but I didn't realize the "%b" directive would match the month abbreviations I'm dealing with. It's described as "Locale's abbreviated month name"; if someone were to run my program on a French system e.g., wouldn't it try to find a match among "jan", "f?v", ..., "d?c" (or whatever) and fail? Is there a way to declare a "locale" that will override the user's settings? Are the locale-specific strings documented anywhere? Can one assume them to be identical in all English-speaking countries, at least? Now it's pretty unlikely in this case that such an 'international situation' will arise, but I didn't want to burn any bridges ... I was also somewhat put off "strptime" on reading the caveat "Note: This function relies entirely on the underlying platform's C library for the date parsing, and some of these libraries are buggy. There's nothing to be done about this short of a new, portable implementation of strptime()." If it works, however, it'll be a lot tidier than what I was doing. I'll make a point of testing it on its own, with a variety of inputs. > Note that the %Z is a problematic entry... > ValueError: time data did not match format: data=03 Feb 2008 > 20:35:46 PST fmt=%d %b %Y %H:%M:%S %Z All the times are UTC, so fortunately this is a non-issue for my purposes of the moment. May I assume that leaving the zone out will cause the time to be treated as UTC? Thanks for your help, and for bearing with my elementary questions and my fumbling about. -- Odysseus From mani.agape at gmail.com Mon Feb 11 10:31:56 2008 From: mani.agape at gmail.com (Manikandan R) Date: Mon, 11 Feb 2008 21:01:56 +0530 Subject: How to broad cast ping address....... Message-ID: <c336cc820802110731w75e7f251td8b3aac46ffd3a1f@mail.gmail.com> Hai, I am working in Python scripting. I an need to find out all the device connected in the network. Just I planned to broad cast the ping address and use the ARP table to get the IP address of the system in the network. As, I am working in Win XP i am not able to use ping -b command to broad cast. I have one more doubt, Is it is possible to see the router table from the client system (My system), since router table will have the Mac / IP address of all the system in the network. If there is any possibilities please mention me. Another option I like to try is to see the DNS table but its not possible from client system (My sytem), I think so. I am trying this for more that 2 week, no result from any one. Please reply me. Thank's in advance. Thank's and Regard's, R.Manikandan. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080211/36282003/attachment.html> From dan at catfolks.net Thu Feb 21 11:11:43 2008 From: dan at catfolks.net (Daniel Mahoney) Date: Thu, 21 Feb 2008 10:11:43 -0600 Subject: Looking for up to date documentation for Python/Tkinter References: <b838b7ed-845a-45d1-815c-f572eba265d1@e23g2000prf.googlegroups.com> Message-ID: <pan.2008.02.21.16.11.41.441343@catfolks.net> On Thu, 21 Feb 2008 07:47:35 -0800, Kintaro wrote: > Oh wise usenet users, > > Please speak unto me the URL which contain the latest documentation on > Python/Tkinter programming. > > I have seen Fredrik Lundh's introduction to tkinter (and others) and > it appears to be for an earlier version of Python. I am working with > Python 2.5 and most doc I am finding are for Python 2.2 or earlier. > > Many thanks One of my favorites is http://effbot.org/tkinterbook/ From bbxx789_05ss at yahoo.com Sun Feb 24 21:07:15 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Sun, 24 Feb 2008 18:07:15 -0800 (PST) Subject: Create multiple directories References: <qf54s3tlimvk3ej421ir6s1k4u5ba5fkai@4ax.com> <SdWdnYDz_67LhF_anZ2dnUVZ_tbinZ2d@comcast.com> Message-ID: <5b42e76f-4b9c-4bdb-93dd-915b1bb26357@z17g2000hsg.googlegroups.com> On Feb 24, 6:27?pm, Jeff Schwab <j... at schwabcenter.com> wrote: > Paul Lemelle wrote: > > I am somewhat new to Python and I am trying to create a program that > > automatically creates directories from a range of numbers. I > > researched the os.mkdir & os.makedirs methods, but they do not seem to > > (I don't know) how to include an argumnet to step through my list. > > > I woudl like to do the follwoing: > > 1) Ask the user how many folders to create > > 2) take raw_input and then translate it into a while loop that steps > > through the os.mkdir process. > > Maybe something like this? > > import os > > def mkdirs(n): > ? ? ?for i in range(n): > ? ? ? ? ?os.mkdir("%d" % i) > > if __name__ == '__main__': > ? ? ?mkdirs(int(raw_input("How many folders should I create? "))) Maybe something like this: import os num_str = raw_input("Enter number of dirs to create: ") num = int(num_str) for i in range(num): dir_name = "new_dir%s" % i #same result as "new_dir" + str(i) os.mkdir(dir_name) #creates dirs in current directory From __peter__ at web.de Thu Feb 21 11:18:16 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 21 Feb 2008 17:18:16 +0100 Subject: exec and closures References: <47bd878a$0$30988$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <fpk887$uu6$02$2@news.t-online.com> Alejandro Dubrovsky wrote: > About a month ago, there was a thread on auto-assigning decorators for > __init__. One by Andr? Roberge is here: > http://groups.google.com/group/comp.lang.python/browse_frm/ > thread/32b421bbe6caaeed/0bcd17b1fa4fb07c?#0bcd17b1fa4fb07c > > This works well for simple cases, but doesn't take keyword arguments or > set default values. I wrote a more extensive version implementing python > call semantics, but it seemed awkard to be repeating something the > compiler does already, so I tried execing a function definition on the > fly with the right parameters that would function as the decorator. Like > this (adjust the indentation variable if it throws a syntax error) > > def autoassign(_init_): > import inspect > import functools > > argnames, _, _, defaults = inspect.getargspec(_init_) > argnames = argnames[1:] > > indentation = ' ' > settings = ['self.%s = %s' % (arg[1:], arg) for arg in argnames > if arg[0] == '_'] > > if len(settings) <= 0: > return _init_ > > if defaults is None: > args = argnames[:] > else: > args = argnames[:-len(defaults)] > for key, value in zip(argnames[-len(defaults):],defaults): > args.append('%s=%s' % (key, repr(value))) > > template = """def _autoassign(self, %(args)s): > %(setting)s > _init_(self, %(argnames)s) > """ % {'args' : ", ".join(args), 'setting' : "\n".join(['%s%s' % > (indentation, setting) for setting > in settings]), 'argnames' : ', '.join(argnames)} > > try: > exec template > except SyntaxError, e: > raise SyntaxError('%s. line: %s. offset %s:\n%s' % > (e.msg, e.lineno, e.offset, template)) > return _autoassign > > > Which creates what looked like the right template, but when instantiating > a class that uses that (eg > class A(object): > @autoassign > def __init__(self,_a): > pass > a = A(3) > > it throws a > NameError: global name '_init_' is not defined > > Is there a way to bind the _init_ name at exec time? Use a dedicated namespace: namespace = dict(_init_=_init_) exec template in namespace return namespace["_autoassign"] Peter From istvan.albert at gmail.com Tue Feb 5 17:32:37 2008 From: istvan.albert at gmail.com (Istvan Albert) Date: Tue, 5 Feb 2008 14:32:37 -0800 (PST) Subject: IronPython vs CPython: faster in 1.6 times? References: <52c34392-5c5b-49b8-8c75-ba9add438b73@k39g2000hsf.googlegroups.com> <caacf668-cafc-457c-abfc-042d8fc82a95@m34g2000hsf.googlegroups.com> <2995994a-487c-4797-ad01-0989cd9ea40a@l16g2000hsh.googlegroups.com> Message-ID: <92b1ee27-2cc8-46b2-8a29-05b74ee823e1@b2g2000hsg.googlegroups.com> On Feb 5, 4:56 pm, Arnaud Delobelle <arno... at googlemail.com> wrote: > Could it be because .NET doesn't have arbitrary length integer types > and your little benchmark will create lots of integers > 2**32 ? > What is the result if you replace foo(a) with > def foo(a): return sqrt(a) Good observation, in the case above the run times are about the same. i. From pavlovevidence at gmail.com Thu Feb 14 19:17:49 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 14 Feb 2008 16:17:49 -0800 (PST) Subject: RELEASED Python 2.5.2, release candidate 1 References: <mailman.792.1203024506.9267.python-list@python.org> <87skzv17ot.fsf@benfinney.id.au> <47b4cbe7$0$20024$9b622d9e@news.freenet.de> Message-ID: <43da834e-7a3a-483d-81f0-ac3f3f0a4ffa@u10g2000prn.googlegroups.com> On Feb 14, 6:16 pm, "Martin v. L?wis" <mar... at v.loewis.de> wrote: > >> On behalf of the Python development team and the Python community, I'm > >> happy to announce the release of Python 2.5.2 (release candidate 1). > > > Um. If it's only a release *candidate* of 2.5.2, and not yet a > > *release* of 2.5.2, could you please announce it as something other > > than a "release"? > > > It should either be announced as "the release of Python 2.5.2", if > > that's the case; or "the availability of the Python 2.5.2 release > > candidate 1". > > Please accept my apologies. I'm not a native speaker, so "to release" > means to me what the dictionary says it means: m-w's fourth meaning, > "make available to the public". That's what I did - I made the release > candidate available to the public. > > So is the subject incorrect as well? If so, what should it say? I think it's fine as it is. You can "release" a release candidate. Carl Banks From andre.roberge at gmail.com Sun Feb 24 16:06:52 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Sun, 24 Feb 2008 13:06:52 -0800 (PST) Subject: urllib slow on Leopard References: <47c1cc1f$0$21099$da0feed9@news.zen.co.uk> Message-ID: <8b14056a-e730-4d70-b62a-a91f9b7696cc@i12g2000prf.googlegroups.com> On Feb 24, 3:57 pm, mark <m... at privacy.net> wrote: > I've recently switched from Ubuntu to OS X Leopard. I have some python > scripts which download info from the web. The scripts were working fine > before on Ubuntu, but urllib seems to work really slowly on Leopard. > > I tried an example from the docs: > > >>> import urllib2 > >>> f = urllib2.urlopen('http://www.python.org/') > >>> print f.read(100) > <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" > "http://www.w3.org/TR/xhtml1/DTD/xhtm > >>> > > The line f = ... takes about a minute to return - but otherwise returns > the predicted result. My web connection seems fine, so has anyone got > any ideas as to what the problem might be? Nope, but it's not Leopard related. Just checked here and it loaded in about 1 sec. Andr? From castironpi at gmail.com Sat Feb 16 18:43:34 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 16 Feb 2008 15:43:34 -0800 (PST) Subject: An idea for fast function composition References: <mailman.863.1203198477.9267.python-list@python.org> <2c092327-38d0-4624-8b24-a8a8a414b078@d5g2000hsc.googlegroups.com> Message-ID: <c4cddc01-9100-403c-add8-5b71a1e9e78c@j28g2000hsj.googlegroups.com> > def compose( funcs ): > ? ?def reccompose( *args ): > ? ? ? return compose( funcs[:-1] )( funcs[-1]( *args ) ) if funcs else > funcs[0]( *args ) > ? ?return reccompose- Hide quoted text - Which was, if funcs> 1, which is len( funcs )> 1. >>> [1]>0 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unorderable types: list() > int() From fuzzyman at gmail.com Wed Feb 6 19:16:14 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Wed, 6 Feb 2008 16:16:14 -0800 (PST) Subject: Is there a way to use .NET DLL from Python References: <85706ba0-8c24-4324-9a79-98c97fc802db@e4g2000hsg.googlegroups.com> Message-ID: <1515475c-72c8-459a-a7c6-dd9e511f9659@c4g2000hsg.googlegroups.com> On Feb 6, 9:27 pm, Huayang Xia <huayang.... at gmail.com> wrote: > Hello All, > > I have several .NET DLL (I have no source code for them), is there > anyway to use them from python instead of from C#. > > Thanks, > Huayang To access .NET types you either need to use IronPython or Python.NET. .NET assemblies are dependent on the .NET runtime to do anything and so can't be accessed with ctypes as other DLLs can. Michael Foord http://www.manning.com/foord From bhuta.darshan at gmail.com Tue Feb 26 14:05:20 2008 From: bhuta.darshan at gmail.com (john_sm3853) Date: Tue, 26 Feb 2008 11:05:20 -0800 (PST) Subject: Adobe CS3 Message-ID: <15662975.post@talk.nabble.com> Hey guys wondering, if you are using Adobe CS3 and do you think, if there are other alternatives to CS3. Would you recommend CS3 or wait for something else. -- View this message in context: http://www.nabble.com/Adobe-CS3-tp15662975p15662975.html Sent from the Python - python-list mailing list archive at Nabble.com. From cwitts at gmail.com Wed Feb 13 13:53:53 2008 From: cwitts at gmail.com (Chris) Date: Wed, 13 Feb 2008 10:53:53 -0800 (PST) Subject: Cannot understand error message References: <PaOdnQnFb6oMtS7anZ2dneKdnZydnZ2d@bt.com> Message-ID: <215d3d59-2204-44b0-bfdb-c7de8fb1f12f@e23g2000prf.googlegroups.com> On Feb 13, 7:29 pm, "Bill Davy" <B... at SynectixLtd.com> wrote: > The following code produces an error message (using Idle with Py 2.4 and > 2.5). "There's an error in your program: EOL while scanning single-quoted > string". It comes just after "s = ''" (put there to try and isolate the > broken string). > > It would be good if the error message pointed me to the start of said single > quoted string. > > The colouring in IDLE does not indicate a bad string. > > Puzzled. > > Bill > > # > > # The traceback module is used to provide a stack trace to > > # show the user where the error occured. See Error(). > > # > > import traceback > > # > > # The math module is used to convert numbers between the Python real format > > # and the Keil real format. See KeilToFloatingPoint() and FloatingToKeil(). > > # > > import math > > LOAD_LIT = 1 > > LOAD_REG = 1 > > STORE_REG = 1 > > ADD_LIT_FP = 2 + 8 > > ADD_LIT_INT = 2 + 16 > > ADD_REG_FP = 2 + 32 > > ADD_REG_INT = 9 > > SUB_LIT_FP = 11 > > SUB_LIT_INT = 12 > > SUB_REG_FP = 13 > > SUB_REG_INT =14 > > MUL_LIT_FP = 11 > > MUL_LIT_INT = 12 > > MUL_REG_FP = 13 > > MUL_REG_INT =14 > > DIV_LIT_FP = 11 > > DIV_LIT_INT = 12 > > DIV_REG_FP = 13 > > DIV_REG_INT =14 > > AND_LIT_INT = 12 > > AND_REG_INT =14 > > OR_LIT_INT = 12 > > OR_REG_INT =14 > > NEGATE_FP = 11 > > NEGATE_INT = 12 > > ABSOLUTE_FP = 13 > > ABSOLUTE_INT = 14 > > INVERT_INT = 15 > > JUMP_OPCODE = 15 > > JLT_OPCODE = 15 > > JGT_OPCODE = 15 > > JLE_OPCODE = 15 > > JGE_OPCODE = 15 > > JEQ_OPCODE = 15 > > JNE_OPCODE = 15 > > BinaryOps={ > > "LOAD":{float:{"L":LOAD_LIT,"R":LOAD_REG},int:{"L":LOAD_LIT,"R":LOAD_REG}}, > > "STORE":{float:{"R":STORE_REG},int:{"R":STORE_REG}}, > > "ADD":{float:{"L":ADD_LIT_FP,"R":ADD_REG_FP},int:{"L":ADD_LIT_INT,"R":ADD_REG_INT}}, > > "SUB":{float:{"L":SUB_LIT_FP,"R":SUB_REG_FP},int:{"L":SUB_LIT_INT,"R":SUB_REG_INT}}, > > "MUL":{float:{"L":MUL_LIT_FP,"R":MUL_REG_FP},int:{"L":MUL_LIT_INT,"R":MUL_REG_INT}}, > > "DIV":{float:{"L":DIV_LIT_FP,"R":DIV_REG_FP},int:{"L":DIV_LIT_INT,"R":DIV_REG_INT}}, > > "AND":{int:{"L":AND_LIT_INT,"R":AND_REG_INT}}, > > "OR":{int:{"L":OR_LIT_INT,"R":OR_REG_INT}} > > } > > UnaryOps={ > > "NEGATE":{float:NEGATE_FP, int:NEGATE_INT}, > > "ABSOLUTE":{float:ABSOLUTE_FP, int:ABSOLUTE_INT}, > > "INVERT":{int:INVERT_INT} > > } > > JumpOps={ > > "JUMP":JUMP_OPCODE, > > "JLT":JLT_OPCODE, > > "JGT":JGT_OPCODE, > > "JLE":JLE_OPCODE, > > "JGE":JGE_OPCODE, > > "JEQ":JEQ_OPCODE, > > "JNE":JNE_OPCODE > > } > > def IsOpCode(s): > > if ( s in BinaryOps ): return True; > > if ( s in UnaryOps ): return True; > > if ( s in JumpOps ): return True; > > return False > > class Register: > > """ > > This class provides us with a register (say) 0..32 > > In addtion to a number, a register can be given a name. > > It allows LOAD(arg) and other opcodes to distinguish between > > references to a register and a literal value. > > """ > > def __init__(self,Id,Name=None): > > self.Number = Id > > if ( Name == None): > > self.Name = "R%d" % Id > > else: > > self.Name = Name > > def RegisterNumber(self): > > return self.Number > > def RegisterName(self): > > return self.Name > > R0=Register(0) > > R1=Register(1) > > R2=Register(2) > > Now=Register(2,"Now") > > def IsRegister(arg): > > return hasattr( arg, "RegisterNumber") > > assert not IsRegister(0) > > assert not IsRegister(1.2) > > assert IsRegister(R1) > > assert IsRegister(Now) > > # > > # ErrorCount is global as it is shared by all slaves. > > # > > ErrorCount = 0 > > def Error(Message): > > """ > > work back through the traceback until you find a function whose name is > in one of the > > opcode dictionaries and trace back from there. This will keep internal > > implemenataion functions private but still allow the suer to define > functions > > that generate code. > > """ > > global ErrorCount > > ErrorCount += 1 > > """ > > [ > > ('<string>', 1, '?', None), > > ('C:\\Python24\\lib\\idlelib\\run.py', 90, 'main', 'ret = method(*args, > **kwargs)'), > > ('C:\\Python24\\lib\\idlelib\\run.py', 283, 'runcode', 'exec code in > self.locals'), > > ('H:\\Husky Experiments\\Viper1\\tmp.py', 434, '?', 'STORE(1)'), > > ('H:\\Husky Experiments\\Viper1\\tmp.py', 147, 'STORE', > 'self.BINOP("STORE",Arg,Msg)'), > > ('H:\\Husky Experiments\\Viper1\\tmp.py', 198, 'BINOP', 'return > Error("Cannot perform %s on %s" % (Op,Arg))'), > > ('H:\\Husky Experiments\\Viper1\\tmp.py', 106, 'Error', 'tb = > traceback.extract_stack()') > > ] > > """ > > tb = traceback.extract_stack() > > BeforePrinting = True > > IsPrinting = False > > for i in range(len(tb)-1,0,-1): > > frame = tb[i] > > if ( BeforePrinting ): > > # Looking to start > > if IsOpCode(frame[2]): # start printing > > IsPrinting = True > > BeforePrinting = False > > print "John: %s\nTrace back follows:" % Message > > elif ( IsPrinting ): > > print '\tFile "%s", line %u, %s' % (frame[0], frame[1], > frame[3]) > > # Stop when we find the curious function "?" > > if (frame[2] == "?"): > > break > > if BeforePrinting: > > print "John: %s (no trace back)" % Message > > class Slave: > > "This is a slave class" > > Listing = "" > > Number = 0 > > Mode = 0; # Will be int or float when defined > > def __init__(self,Id): > > self.Number = Id > > self.Line = 0 > > # > > # The listing, built as we go along > > # > > self.Listing = "" > > self.Mode = None > > def SetMode(self, arg): > > self.Mode = arg > > def LOAD(self,Arg,Msg=""): > > self.BINOP("LOAD",Arg,Msg) > > def STORE(self,Arg,Msg=""): > > self.BINOP("STORE",Arg,Msg) > > def ADD(self,Arg,Msg=""): > > self.BINOP("ADD",Arg,Msg) > > def SUB(self,Arg,Msg=""): > > self.BINOP("SUB",Arg,Msg) > > def MUL(self,Arg,Msg=""): > > self.BINOP("MUL",Arg,Msg) > > def DIV(self,Arg,Msg=""): > > self.BINOP("DIV",Arg,Msg) > > def AND(self,Arg,Msg=""): > > self.BINOP("AND",Arg,Msg) > > def OR(self,Arg,Msg=""): > > selfBINOPOP("OR",Arg,Msg) > > def NEGATE(self,Msg=""): > > self.UNOP("NEGATE",Msg) > > def ABSOLUTE(self,Msg=""): > > self.UNOP("ABSOLUTE",Msg) > > def INVERT(self,Msg=""): > > self.UNOP("INVERT",Msg) > > def JUMP(self,Arg,Msg=""): > > self.JUMPOP("JUMP",Arg,Msg) > > def JLT(self,Arg,Msg=""): > > self.JUMPOP("JLT",Arg,Msg) > > def JGT(self,Arg,Msg=""): > > self.JUMPOP("JGT",Arg,Msg) > > def JLE(self,Arg,Msg=""): > > self.JUMPOP("JLE",Arg,Msg) > > def JGE(self,Arg,Msg=""): > > self.JUMPOP("JGE",Arg,Msg) > > def JEQ(self,Arg,Msg=""): > > self.JUMPOP("JEQ",Arg,Msg) > > def JNE(self,Arg,Msg=""): > > self.JUMPOP("JNE",Arg,Msg) > > def BINOP(self,Op,Arg,Msg): > > entry = BinaryOps.get(Op) > > assert entry != None, "Who gave me %s to look up?" % op > > entry = entry.get(self.Mode) > > if entry == None : > > return Error("Cannot perform %s on %s, mode=%s" % ( > > Op,Arg,self.Mode)) > > if ( IsRegister(Arg) ): > > ot = entry.get("R") # Register > > if ot == None: > > return Error("Cannot perform %s on %s" % (Op,Arg)) > > self.Listing += "%x \t \t%s\t%s\t# %s\n" % ( > > len(self.Memory), Op,Arg.RegisterName(), Msg) > > self.Memory.append(ot) > > self.Memory.append(Arg.RegisterNumber()) > > else: > > ot = entry.get("L") # Literal > > if ot == None: > > return Error("Cannot perform %s on %s" % (Op,Arg)) > > self.Listing += "%x \t \t%s\t%s\t# %s\n" % ( > > len(self.Memory), Op, Arg, Msg) > > self.Memory.append(ot) > > cArg = self.Mode(Arg) > > if self.Mode == int: > > try: > > iArg = int(Arg) > > except TypeError: > > return Error("Argument %r is not an integer" % Arg) > > except: > > return Error("Unexpected error:", sys.exc_info()[0]) > > if ( iArg != Arg ): > > return Error("Argument %r is not an integer" % Arg) > > self.Memory.append((iArg >> 24) & 0xFF) > > self.Memory.append((iArg >> 16) & 0xFF) > > self.Memory.append((iArg >> 8) & 0xFF) > > self.Memory.append((iArg >> 0) & 0xFF) > > elif self.Mode == float: > > try: > > fArg = float(Arg) > > except TypeError: > > return Error("Argument %r is not a float" % Arg) > > except: > > return Error("Unexpected error:", sys.exc_info()[0]) > > if ( fArg != Arg ): > > return Error("Argument %r is not a float" % Arg) > > FourBytes = FloatingToKeil(fArg) > > self.Memory.append(FourBytes[0]) > > self.Memory.append(FourBytes[1]) > > self.Memory.append(FourBytes[2]) > > self.Memory.append(FourBytes[3]) > > else: > > return Error("No or bad mode (%r)set for slave %u" % ( > > self.Mode,self.SlaveNumber)) > > def JUMPOP(self,Op,Name,Msg): > > entry = JumpOps.get(Op) > > assert entry != None, "Who gave me %s to look up?" % op > > """ > > Generate code for a jump to the given target > > May enter target into the table. > > """ > > self.Listing += "%x \t \t%s\t%s\t# %s\n" % ( > > len(self.Memory),Op,Name, Msg) > > self.Memory.append(entry) > > self.AddReference(Name,len(self.Memory)) # for patching up later > > self.Memory.append(0) # Space for destination of jump > > # > > # The memory image of this Slave. > > # > > Memory = [] > > def ListProgram(self): > > """Generate a user friendly listing of the program for this Slave. > > """" > > s = '' > > print "%s" % self.Number > > print "%s\n" % ("#" * 64) > > print "%s" % self.Listing > > pass > > def EmitProgram(self): > > """Emit a C code data structure of the program for this Slave. > > """ > > s=\ > > "%s\n/* C data structure for slave %d */\n"\ > > "struct\n"\ > > "\t{\n"\ > > "\tunsigned SlaveId;\n"\ > > "\tunsigned nBytes;\n"\ > > "\tunsigned char[%d];\n"\ > > "\t} Slave%d=\n"\ > > "\t{%u,%u\n"\ > > "\t{\n\t"\ > > % ('#'*64, self.Number, len(self.Memory), self.Number, self.Number, > len(self.Memory)) > > for i in range(0,len(self.Memory)): > > if (i>0) : s+= ", " > > s += "0x%x" % (self.Memory[i]) > > if ( (i % 16) == 15 ): > > s += '\n\t' > > s+="\n\t}\n\t};\n" > > print s; > > # > > # Dictionary of Labels > > # Maps Name onto (Set of Locations, List of references)) > > # Users define a label using Label(Name) > > # Users reference a label using Jump(Name) > > # > > LabelTable = {} > > def AddReference(self,Name,Reference): > > """ > > Add a reference to the given Name. > > Name may not yet be defined > > """ > > Entry = self.LabelTable.get(Name) > > if ( Entry == None ): > > self.LabelTable[Name] = [ [] , [Reference] ] > > else: > > Entry[1].append(Reference) > > def AddDefinition(self,Name,Location): > > """ > > Add a definition to the given Name. > > Name may not yet be defined. > > If it is defined, it may not be given a different Location. > > """ > > Entry = self.LabelTable.get(Name) > > if ( Entry == None ): > > # Add location to a new name > > self.LabelTable[Name] = [ [Location] , [] ] > > elif len(Entry[0]) == 0: > > # Provide an initial location for a known name > > Entry[0].append(Location) > > elif Entry[0].count(Location) == 1: > > # The same location, harmless but odd > > pass > > else: > > # This is an additional definition but that does not matter > > # unless it is used and we find that out when we call > FixUpLabels() > > # at the end. > > Entry[0].append(Location) > > def Label(self, Name, Msg=""): > > """ > > Lays down a label for the user. > > """ > > self.AddDefinition(Name,len(self.Memory)) > > self.Listing += "%x \t%s: \t \t \t# %s\n" % (len(self.Memory), Name, > Msg) > > def EmitLabelTable(self): > > print "%s\nSymbol table for Slave %u" % ('#' * 64, self.Number) > > for Name in self.LabelTable.keys(): > > s = "Name=%s" % Name > > entry = self.LabelTable[Name] > > if ( len(entry[0])==1 and len(entry[1]) == 0): > > s += ", is not referenced" > > if ( len(entry[0])==0 and len(entry[1]) > 0): > > s += ", is not defined" > > if ( len(entry[0])>1 and len(entry[1]) > 0): > > s += ", is multiply-defined" > > if ( len(entry[0]) > 0): > > s += ", Location:" > > for i in entry[0]: > > s += " %x" % i > > if ( len(entry[1]) > 0 ): > > s += ", references:" > > for i in range(0,len(entry[1])): > > s += " %x" % entry[1][i] > > print s > > def FixUpLabels(self): > > print "%s\nFixing labels for Slave %u" % ('#' * 64, self.Number) > > for Name in self.LabelTable.keys(): > > entry = self.LabelTable[Name] > > if ( len(entry[0])==1 and len(entry[1]) == 0): > > print "Warning: %s is not referenced" % Name > > elif ( len(entry[0])==0 and len(entry[1]) > 0): > > Error("%s is not defined" % Name) > > elif ( len(entry[0])>1 and len(entry[1]) > 0): > > Error("%s is multiply-defined" % Name) > > else: > > for i in range(0,len(entry[1])): > > self.Memory[entry[1][i]] = entry[0][0] > > # > > # Construct a vector of Slaves > > # > > S=[(Slave(i)) for i in range(6)] > > def SetSlave(New): > > """ > > Make global functions generate code for a specified slave. > > """ > > # > > # This sets the mode for the assembler and applies in the order of > > # assembly, not in the execution order. The mode is embedded in the > opcode. > > # > > global SetMode > > SetMode = S[New].SetMode > > # > > # Labels are local to a slave. > > # > > global Label > > Label = S[New].Label; > > global LOAD, STORE, ADD, SUB, MUL, DIV, AND, OR > > global NEGATE, ABSOLUTE, INVERT > > global JUMP, JLT, JGT, JLE, JGE, JEQ, JNE > > LOAD = S[New].LOAD > > JUMP = S[New].JUMP > > LOAD = S[New].LOAD > > STORE = S[New].STORE > > ADD = S[New].ADD > > SUB = S[New].SUB > > MUL = S[New].MUL > > DIV = S[New].DIV > > AND = S[New].AND > > OR = S[New].OR > > NEGATE = S[New].NEGATE > > ABSOLUTE = S[New].ABSOLUTE > > INVERT = S[New].INVERT > > JUMP = S[New].JUMP > > JLT = S[New].JLT > > JGT = S[New].JGT > > JLE = S[New].JLE > > JGE = S[New].JGE > > JEQ = S[New].JEQ > > JNE = S[New].JNE > > print "hi" > > SetSlave(1) > > SetMode(int) > > LOAD(4,"Into S1 hopefully") > > Label("Loop") > > LOAD(R1,"Comment") > > JUMP("Loop") > > LOAD(Now) > > JUMP("Loop") > > STORE(1) > > Label("Loop") > > class TemporaryLabelClass: > > DefaultBaseName = "TL_" > > Instances = {DefaultBaseName:0} > > def __init__(self, BaseName=None): > > de = self.Instances.get(BaseName) > > if de == None: > > self.Instances[BaseName] = 0 # new temporary BaseName > > else: > > self.Instances[BaseName] += 1 # using an existing BaseName again > > self.BaseName = BaseName; > > def Instance(self): > > return self.Instances[self.BaseName] > > def TemporaryLabel(BaseName=None): > > t = TemporaryLabelClass(BaseName) > > if ( BaseName == None ): > > BaseName = t.DefaultBaseName > > elif ( BaseName == t.DefaultBaseName): > > return Error("Do not call TemporaryLabel(%s)" % t.DefaultBaseName) > > return "%s%u" % (BaseName,t.Instance()) > > a = TemporaryLabel() > > b = TemporaryLabel("MY") > > c = TemporaryLabel() > > d = TemporaryLabel("MY") > > e = TemporaryLabel() > > f = TemporaryLabel("TL_") > > del a, b, c, d, e, f > > def BusyIdleLoop(Time, Register): > > label = TemporaryLabel() > > LOAD(Now) > > ADD(Time) > > STORE(Register) > > Label(label) > > LOAD(Now) > > SUB(Register) > > JLT(label) > > BusyIdleLoop(5000,R0) > > S[1].FixUpLabels() > > S[1].EmitProgram() > > S[1].EmitLabelTable() > > S[1].ListProgram() > > def KeilToFloatingPoint(Bytes): > > #print Bytes > > temp = ((((((Bytes[0]<<8)+Bytes[1])<<8)+Bytes[2])<<8)+Bytes[3]) > > if ( temp == 0): > > return 0.0 > > Mantissa = 0x800000 + (temp&0x7fffff) > > if ( temp & 0x80000000 ): > > Mantissa = -Mantissa > > temp -= 0x80000000 > > Exponent = (0xFF & (temp>>23)) - 127; > > Mantissa = float(Mantissa) / (1<<23) > > #print "Mantissa=%f" % Mantissa > > #print "Exponent=%x" % Exponent > > return math.ldexp(Mantissa, Exponent) > > def FloatingToKeil(arg): > > """ > > The flooating point format used by Keil follows > > the IEEE-754 standard > > The fields are (from MSB to LSB, and first byte to last): > > S (one bit) 1 is posirtive, 0 is negative > > E (eight bits) Exponent + 127 > > M (23 bits) The twenty four bit (MSB omitted) mantissa > > """ > > Mantissa, Exponent = math.frexp( arg ) > > Mantissa *= 2 > > Exponent -= 1 > > if ( Mantissa >= 0 ): > > if ( Exponent == 0 ): > > return (0,0,0,0) > > S = 0 > > else: > > S = 1 > > Mantissa = -Mantissa > > Mantissa *= (1<<23) > > Mantissa = int(Mantissa + 0.5) # round > > if ( Mantissa >> 24 ): > > # Renormalise > > Mantissa >>= 1 > > Exponent += 1 > > assert ( (Mantissa >> 24) == 0) > > Mantissa -= (1<<23) # Remove the "assumed" 1 before the binary point > > assert ( (Mantissa >> 23) == 0 ) > > Exponent += 127 > > if ( Exponent < 0 ): > > # Number is too small to represent; call it zero > > FourBytes = 0,0,0,0 > > temp = KeilToFloatingPoint(FourBytes) > > print "Truncating %r to %r" % (arg, temp) > > elif ( Exponent > 0xFF): > > # Number is too big to represent; make the maximum with the right > sign > > FourBytes = (S<<7)+0x7F,0xFF,0xFF,0xFF > > temp = KeilToFloatingPoint(FourBytes) > > print "Truncating %r to %r" % (arg, temp) > > else: > > temp = (S<<31) + (Exponent<<23) + Mantissa > > FourBytes = ((temp>>24),0xFF&(temp>>16),0xFF&(temp>>8),0xFF&(temp)) > > temp = KeilToFloatingPoint(FourBytes) > > return FourBytes > > FloatingToKeil(-12.5) > > FloatingToKeil(-1e-200) ## should become zero > > FloatingToKeil(-1e+200) ## should saturate > > FloatingToKeil(math.ldexp((1<<24)-1,-24)) ## Exact conversion > > FloatingToKeil(math.ldexp((1<<25)-1,-25)) ## Should make renormalise happen > > print "Byeee" Just before s = '' you have 4 double quotes to close to doc-string instead of 3. From DustanGroups at gmail.com Mon Feb 4 11:45:43 2008 From: DustanGroups at gmail.com (Dustan) Date: Mon, 4 Feb 2008 08:45:43 -0800 (PST) Subject: Python feature request : operator for function composition References: <b9c459d2-3768-4242-870d-64d0e0ab98ed@v17g2000hsa.googlegroups.com> <780065ac-d448-4851-866e-8cbcc8e59ce7@z17g2000hsg.googlegroups.com> <bd59e81a-06c2-4708-9d47-228ec264b350@f47g2000hsd.googlegroups.com> Message-ID: <504fcddf-2fd4-4fc5-b4a8-e42791220a31@m62g2000hsb.googlegroups.com> On Feb 4, 10:11 am, Arnaud Delobelle <arno... at googlemail.com> wrote: > This is nice. Thanks. > * I wouldn't choose '&' as the composing operator as when I read > 'double & square' I think 'take an x, double it & square it' which is > the wrong interpretation (perhaps << instead?). A very good point that I didn't think about; I just blindly took the OP's chosen operator. Another thing I realized after writing this was that I could have also written a corresponding __rand__ method (__rlshift__ with your alternative operator), in case the object to the right of the operator is a composer object and to the left is a simple function. > * I would call the decorator 'composable'. The thing about that, though, is that this can also be used as a composition in function style. However, I can't think of any name that encompasses both uses. And you're right in that composer wasn't a very good choice of name. As I say, it was written in haste. From bobdebm at gmail.com Wed Feb 20 14:45:30 2008 From: bobdebm at gmail.com (Bob and Deb) Date: Wed, 20 Feb 2008 11:45:30 -0800 Subject: scanf in python? Message-ID: <7a3148720802201145o5ece6285y9d5ff81365c7f322@mail.gmail.com> Hello python-list, This is my first post and yes I am a python newbie :-) I've been trying to figure out how to convert an old database dump into a form that can be imported into Postgresql. The file (dealing with one table) looks something like this: create table table1 (id int, name char(20), agw_map char(14), agw real) id 1 11 name 13 32 agw 34 47 6195 000036_00195 26.728 6188 000036_00188 31.905 6217 000036_00223 19.644 6078 000036_00024 38.055 6079 000036_00025 37.678 6080 000036_00027 40.03 6081 000036_00028 38.884 6082 000036_00030 43.616 6083 000036_00032 46.548 6084 000036_00033 48.593 6085 000036_00036 53.764 ****** End of Table ****** In C I could build a format string (using info from the table create statement and the column position in the header) and use scanf to parse this file. What does the Python solution looks like? Thanks in advance. Bob -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080220/46324d76/attachment.html> From jeff at schwabcenter.com Mon Feb 18 21:34:40 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Mon, 18 Feb 2008 18:34:40 -0800 Subject: name of client module In-Reply-To: <mailman.943.1203387358.9267.python-list@python.org> References: <2KCdnWJQeaBuuCfanZ2dnUVZ_sednZ2d@comcast.com> <mailman.943.1203387358.9267.python-list@python.org> Message-ID: <qYydnSxkU4OB3SfanZ2dnUVZ_vyinZ2d@comcast.com> Nick Stinemates wrote: > Jeff Schwab wrote: >> Q1: When a module is imported, is there any way for the module to >> determine the name of the client code's module? >> > Why would you ever want to do this? >> Q2: My understanding is that the code in a module is executed only on >> the first import of that module. Is there any way to have a hook >> invoked on subsequent imports, and for that hook (as in Q1) to determine >> the name of the client module? >> > Why would you ever want to do this? So that the imported module can implement functions that return information about the client module, as a form of introspection. Suppose I want to know whether I'm the main module, and I don't want to write __name__ == '__main__'; it would be nice if I could import a module and call a method to tell me whether I'm __main__: import modinfo if modinfo.main(): print("Hello, world") > I don't really understand why you wouldn't want to do the following: > > import foo > foo.exec() I'm not saying I don't want to do that. I'm saying that, in addition to what you've written, I want foo to know it's being imported, and by whom. From willsteve2003 at yahoo.ca Fri Feb 1 11:37:47 2008 From: willsteve2003 at yahoo.ca (rockingred) Date: Fri, 1 Feb 2008 08:37:47 -0800 (PST) Subject: PyWeek 6 is coming! References: <mailman.132.1201836802.9267.python-list@python.org> Message-ID: <22b540b4-3698-48ba-a50a-06ed5790181a@v67g2000hse.googlegroups.com> On Jan 31, 4:11?pm, rich... at pyweek.org wrote: > PyWeek 6 will run from 00:00 UTC on March 30th through to 00:00 UTC on April > 6th. > > Registration is NOT OPEN YET. It will open on Friday 2008/02/29. > > If you're new (or even coming back again) please have a look at the rules and > help pages athttp://www.pyweek.org/ > > The PyWeek challenge: > > ? ?1. Invites entrants to write a game in one week from scratch either as an > ? ? ? individual or in a team, > ? ?2. Is intended to be challenging and fun, > ? ?3. Will hopefully increase the public body of game tools, code and > ? ? ? expertise, > ? ?4. Will let a lot of people actually finish a game, and > ? ?5. May inspire new projects (with ready made teams!) > > Entries must be developed in Python during the challenge, and must incorporate > some theme decided at the start of the challenge. > > -- > Visit the PyWeek website: > ?http://www.pyweek.org/ I've added this to Python-forum.org. From paddy3118 at googlemail.com Sat Feb 23 11:45:30 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sat, 23 Feb 2008 08:45:30 -0800 (PST) Subject: Return value of an assignment statement? References: <6d945394-739e-4c47-ad71-faaab8f9d566@34g2000hsz.googlegroups.com> <JMudnUZwpdG_byDanZ2dnUVZ_vmlnZ2d@comcast.com> <3cee8292-04bc-4bed-ab73-b9154522fb31@64g2000hsw.googlegroups.com> Message-ID: <d86811a3-2892-4ff1-89b7-b3e30ff22202@u10g2000prn.googlegroups.com> On 21 Feb, 23:33, "bruno.desthuilli... at gmail.com" <bruno.desthuilli... at gmail.com> wrote: > > What you can't do (that I really miss) is have a tree of assign-and-test > > expressions: > > > import re > > pat = re.compile('some pattern') > > > if m = pat.match(some_string): > > do_something(m) > > else if m = pat.match(other_string): > > do_other_thing(m) > > else: > > do_default_thing() > > What you want is: > > for astring, afunc in ((some_string, do_something), (other_string, > do_other_thing)): > m = pat.match(astring) > if m: > afunc(m) > break > else: > do_default_thing() The Bruno transform? :-) From bignose+hates-spam at benfinney.id.au Tue Feb 12 16:34:38 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 13 Feb 2008 08:34:38 +1100 Subject: ways to declare empty set variable References: <56a14$47b1a306$839b8704$9583@news2.tudelft.nl> <f30e545f-4485-4c0a-a9b2-476939818bc6@y5g2000hsf.googlegroups.com> <5099c$47b1a77b$839b8704$11089@news2.tudelft.nl> Message-ID: <87skzxzwnl.fsf@benfinney.id.au> "Sun" <as at hut.at> writes: > I was wondering why can't I use a format as "var = {} " to > "var=list()" in set variable, and decided not to bother with it. Python 3.0 will gain syntax to specify a literal of type 'set' <URL:http://www.python.org/dev/peps/pep-3100/>:: >>> {17, "foo", 12.5} set([17, 'foo', 12.5]) but this won't allow you to declare an empty set literal, because that's already easy with 'set()', and '{}' is taken already for an empty dict literal. -- \ ?Unix is an operating system, OS/2 is half an operating system, | `\ Windows is a shell, and DOS is a boot partition virus.? | _o__) ?Peter H. Coffin | Ben Finney From michael.pearmain at tangozebra.com Mon Feb 11 11:09:57 2008 From: michael.pearmain at tangozebra.com (Mike P) Date: Mon, 11 Feb 2008 08:09:57 -0800 (PST) Subject: CSV Reader References: <43a3a0d8-9425-4bc5-90d3-894fe980d3f7@s19g2000prg.googlegroups.com> <MqWdnZ_62b7N8i3anZ2dnUVZ_gydnZ2d@comcast.com> Message-ID: <4b1e691a-53ff-4cee-8e15-5bf17f2b56ef@i12g2000prf.googlegroups.com> Hi Larry, i'm still getting to grips with python, but rest assured i thinkn it's better for me to write hte code for learnign purposes My basic file is here, it comes up with a syntax error on the startswith line, is this because it is potentially a list? My idea was to get the lines number where i can see Transaction ID and then write out everything from this point into a new datafile. Would a better solution be just to use readlines and search for the string with a counter and then write out a file from there? Any help is greatly appreciated Mike working_CSV = "//filer/common/technical/Research/E2C/Template_CSV/ DFAExposureToConversionQueryTool.csv" import csv f = file(working_CSV, 'rb') reader = csv.reader(f) CSV_lines = "" for data in reader: if lines.startswith("Transaction ID") append.reader.line_num() # there will only be 1 instance of this title at the start of the CSV file writer(Working_csv.csv[, dialect='excel'][, fmtparam]) From pinard at iro.umontreal.ca Fri Feb 15 00:53:35 2008 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Fri, 15 Feb 2008 00:53:35 -0500 Subject: RELEASED: Pymacs 0.23 Message-ID: <20080215055335.GA16146@phenix.progiciels-bpi.ca> Hello to everybody, and Emacs users in the Python community. Here is Pymacs 0.23! There has been a while, so I advise current Pymacs users to switch with caution. All reported bugs have been squashed, if we except one about Emacs quit (C-g) not being obeyed gracefully. A few suggestions have been postponed, to be pondered later. The manual is now in reST format, and everything Allout is gone. Postscript and PDF files are not anymore part of the distribution, you may find them on the Web site, or use the Makefile if you have needed tools. Examples have been moved out of the manual into a new contrib/ subdirectory, which also holds a few new contributions. The example of a Python back-end for Emacs Gnus has been deleted. Python 1.5.2 compatibility has been dropped; use Python 2.2 or better. The Pymacs manual explains installation procedure, now simplified. The pymacs-services script is gone, this should ease installing Pymacs on MS Windows. There is also a small, still naive validation suite. The communication protocol has been revised: more clarity, less magic. Zombie objects are less dreadful by default. The API now supports False and True constants, and Unicode strings (within limits set by Emacs). Special thanks to those who helped me at creating or testing this release. -------------------- Pymacs is a powerful tool which, once started from Emacs, allows both-way communication between Emacs Lisp and Python. Pymacs aims Python as an extension language for Emacs rather than the other way around, and this asymmetry is reflected in some design choices. Within Emacs Lisp code, one may load and use Python modules. Python functions may themselves use Emacs services, and handle Emacs Lisp objects kept in Emacs Lisp space. The main Pymacs site is `http://pymacs.progiciels-bpi.ca/', and you may fetch `http://pymacs.progiciels-bpi.ca/archives/Pymacs.tar.gz'. Report problems and suggestions to `mailto:pinard at iro.umontreal.ca'. -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From dinov at exchange.microsoft.com Tue Feb 12 22:26:24 2008 From: dinov at exchange.microsoft.com (Dino Viehland) Date: Tue, 12 Feb 2008 19:26:24 -0800 Subject: Is there a way to use .NET DLL from Python In-Reply-To: <2298129a-3ca5-41f9-86ed-28805397fd54@f47g2000hsd.googlegroups.com> References: <85706ba0-8c24-4324-9a79-98c97fc802db@e4g2000hsg.googlegroups.com> <6c2845aa-aec5-4b75-852a-551b9cd1d6ab@f10g2000hsf.googlegroups.com> <d088398a-2b33-4a11-b547-f2afc3632a11@i7g2000prf.googlegroups.com> <5845a12f-41dd-4bb3-8684-483e93f55c5f@e25g2000prg.googlegroups.com> <5cbdc3cf-cb84-49e5-b746-2eca0feeb97d@i7g2000prf.googlegroups.com>, <2298129a-3ca5-41f9-86ed-28805397fd54@f47g2000hsd.googlegroups.com> Message-ID: <7AD436E4270DD54A94238001769C2227011CF4BD4E9A@DF-GRTDANE-MSG.exchange.corp.microsoft.com> >> >> Oh, I know what you mean. >> But that was exactly the reason for having a .DLLs folder, isn't it? >> When you place an assembly into this folder, you avoid having to write >> this boilerplate code, and simply import the assembly as you would >> with a normal python module. At least, that?s how it worked in >> previous versions... >No. You have always had to add references to assemblies before being >able to use the namespaces they contain. You even have to do this with >C# in Visual Studio. This *should* work in both IronPython 1.x and IronPyton 2.0 - the catch though is that it's implemented in the default site.py we ship with. So if you do the usual thing and use CPython's Lib directory you'll lose this feature w/o copying it over. From Lythoner at gmail.com Tue Feb 26 14:28:31 2008 From: Lythoner at gmail.com (Lythoner at gmail.com) Date: Tue, 26 Feb 2008 11:28:31 -0800 (PST) Subject: Regular Expression Help Message-ID: <17392f32-4bbc-4a03-b74e-38626d74e403@p73g2000hsd.googlegroups.com> Hi All, I have a python utility which helps to generate an excel file for language translation. For any new language, we will generate the excel file which will have the English text and column for interested translation language. The translator will provide the language string and again I will have python utility to read the excel file target language string and update/generate the resource file & database records. Our application is VC++ application, we use MS Access db. We have string table like this. "STRINGTABLE BEGIN IDS_CONTEXT_API_ "API Totalizer Control Dialog" IDS_CONTEXT "Gas Analyzer" END STRINGTABLE BEGIN ID_APITOTALIZER_CONTROL "Start, stop, and reset API volume flow \nTotalizer Control" END " this repeats..... I read the file line by line and pick the contents inside the STRINGTABLE. I want to use the regular expression while should give me all the entries with in STRINGTABLE BEGIN <<Get what ever put in this>> END I tried little bit, but no luck. Note that it is multi-line string entries which we cannot make as single line Regards, Krish From castironpi at gmail.com Fri Feb 15 14:20:07 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 15 Feb 2008 11:20:07 -0800 (PST) Subject: XML pickle References: <686a4012-1c9e-456e-973c-c1e396f4c060@s8g2000prg.googlegroups.com> <47B3E3A3.1070205@behnel.de> <e04c6733-62b8-4cae-96c5-266ac037ecd4@s8g2000prg.googlegroups.com> <47B488FD.1090502@behnel.de> <c0cf43e7-0186-4d69-94a6-ef930a5e3b89@s13g2000prd.googlegroups.com> <47B49B3E.3060609@behnel.de> <c4a54f0d-8bc2-467b-8a05-64bc071bd8af@i29g2000prf.googlegroups.com> <47B553EF.5080605@behnel.de> <a06ca784-c7ab-43f6-8b21-eecfae79b7b4@i29g2000prf.googlegroups.com> <ad921886-911a-474f-a6b2-2726d7f966a2@e23g2000prf.googlegroups.com> Message-ID: <94b7d97d-6719-4471-acf2-7c396e44bee6@e23g2000prf.googlegroups.com> On Feb 15, 12:07?pm, castiro... at gmail.com wrote: > On Feb 15, 11:10?am, castiro... at gmail.com wrote: > > > > > Can you use set( '{ss}Type' ) somehow? > > > > What is 'ss' here? A prefix? > > > > What about actually reading the tutorial? > > > >http://codespeak.net/lxml/tutorial.html#namespaces > > > > > And any way to make this look > > > > closer to the original? > > > > What's the difference you experience? > > Something else that crept up is: > > <?xml version='1.0' encoding='ASCII'?> > <Workbook xmlns="[hugethingA]"> > ? <Worksheet xmlns:ns0="[hugethingA]" ns0:name="WSheet1"> > ? </Worksheet> > ? <Styles> > ? ? <Style xmlns:ns1="[hugethingA]" ns1:ID="s21"/> > ? </Styles> > </Workbook> > > Which xmlns:ns1 gets "redefined" because I just didn't figure out how > get xmlns:ns0 definition into the Workbook tag. ?But too bad for me. In Economics, they call it "Economy to Scale"- the effect, and the point, and past it, where the cost to produce N goods on a supply curve on which 0 goods costs 0 exceeds that on one on which 0 goods costs more than 0: the opposite of diminishing returns. Does the benefit of encapsulating the specifics of the XML file, including the practice, exceed the cost of it? For an only slightly more complex result, the encapsulated version is presented; and the hand-coded, unencapsulated one is left as an exercise to the reader. book= Workbook() sheet= Worksheet( book, 'WSheet1' ) table= Table( sheet ) row= Row( table, index= '2' ) style= Style( book, bold= True ) celli= Cell( row, styleid= style ) datai= Data( celli, 'Number', '123' ) cellj= Cell( row ) dataj= Data( cellj, 'String', 'abc' ) 46 lines of infrastructure, moderately packed. Note that: etree.XML( etree.tostring( book ) ) succeeds. From gagsl-py2 at yahoo.com.ar Tue Feb 12 16:12:55 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 12 Feb 2008 19:12:55 -0200 Subject: IDLE Won't Start w/o Socket Error--Win XP References: <gansj.8195$0o7.1525@newssvr13.news.prodigy.net> Message-ID: <op.t6fjvtagx6zn5v@gabriel2.softlabbsas.com.ar> En Tue, 12 Feb 2008 18:18:20 -0200, W. Watson <wolf_tracks at invalid.com> escribi?: > After simply trying to write a program with help(MakeQTE), a module, and > having it fail with socket errors, I decided to restart IDLE, thinking I > knew the cause. I'm now getting msgs like: "IDLE's subprocess didn't make > connection. ... firewall may be blocking the connection." I doubt the FW > connection. There's a small X warning dialog that says "Socket Error: > Connection refused." Is there a way to reset IDLE? From the IDLE About box: IDLE executes Python code in a separate process, which is restarted for each Run (F5) initiated from an editor window. The environment can also be restarted from the Shell window without restarting IDLE. (Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet.) From the help: Running without a subprocess: If IDLE is started with the -n command line switch it will run in a single process and will not create the subprocess which runs the RPC Python execution server. This can be useful if Python cannot create the subprocess or the RPC socket interface on your platform. However, in this mode user code is not isolated from IDLE itself. Also, the environment is not restarted when Run/Run Module (F5) is selected. If your code has been modified, you must reload() the affected modules and re-import any specific items (e.g. from foo import baz) if the changes are to take effect. For these reasons, it is preferable to run IDLE with the default subprocess if at all possible. -- Gabriel Genellina From dirkheld at gmail.com Wed Feb 27 17:02:25 2008 From: dirkheld at gmail.com (dirkheld) Date: Wed, 27 Feb 2008 14:02:25 -0800 (PST) Subject: XML expat error References: <babb6775-311d-4f7a-bc03-90f249e34180@s19g2000prg.googlegroups.com> <fq42hd$loe$1@south.jnrs.ja.net> Message-ID: <5fb056d5-55fe-43c8-83f6-54b65da3860d@u69g2000hse.googlegroups.com> On 27 feb, 17:18, "Richard Brodie" <R.Bro... at rl.ac.uk> wrote: > "dirkheld" <dirkh... at gmail.com> wrote in message > > news:babb6775-311d-4f7a-bc03-90f249e34180 at s19g2000prg.googlegroups.com... > > > xml.parsers.expat.ExpatError: not well-formed (invalid token): line > > 554, column 20 > > > I guess that the element I try to read or the XML(which would be > > strange since they have been created with the same code) can't ben > > retrieved. > > It's fairly easy to write non-robust XML generating code, and also > quick to test if one file is always bad. Drop it into a text editor or > Firefox, and take a quick look at line 554. Most likely some random > control character has sneaked in; it only takes (for example) one NUL > to make the document ill-formed. Something strange here. The xml file causing the problem has only 361 lines. Isn't there a way to catch this error, ignore it and continu with the rest of the other files? This is the full error report : Traceback (most recent call last): File "xmltest.py", line 10, in <module> xmldoc = minidom.parse('/Documents/programming/data/xml/'+file) File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/xml/dom/minidom.py", line 1913, in parse return expatbuilder.parse(file) File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/xml/dom/expatbuilder.py", line 924, in parse result = builder.parseFile(fp) File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/xml/dom/expatbuilder.py", line 207, in parseFile parser.Parse(buffer, 0) xml.parsers.expat.ExpatError: not well-formed (invalid token): line 554, column 20 From no-spam at not-existing.invalid Sat Feb 2 07:22:29 2008 From: no-spam at not-existing.invalid (robert) Date: Sat, 02 Feb 2008 13:22:29 +0100 Subject: string split without consumption Message-ID: <fo1na8$p8n$1@news.albasani.net> this didn't work elegantly as expected: >>> ss 'owi\nweoifj\nfheu\n' >>> re.split(r'\A',ss) ['owi\nweoifj\nfheu\n'] >>> re.split(r'\Z',ss) ['owi\nweoifj\nfheu\n'] >>> re.split(r'$',ss) ['owi\nweoifj\nfheu\n'] >>> re.split(r'(?s)$',ss) ['owi\nweoifj\nfheu\n'] >>> re.split(r'(?m)(?s)$',ss) ['owi\nweoifj\nfheu\n'] >>> re.split(r'(?m)$',ss) ['owi\nweoifj\nfheu\n'] >>> re.split(r'(?m)\Z',ss) ['owi\nweoifj\nfheu\n'] >>> re.split(r'(?m)\A',ss) ['owi\nweoifj\nfheu\n'] >>> re.split(r'(?s)\A',ss) ['owi\nweoifj\nfheu\n'] >>> re.split(r'(?s)(?m)\A',ss) ['owi\nweoifj\nfheu\n'] >>> how to do? Robert From matthias.vogelgesang at gmail.com Sat Feb 23 09:43:59 2008 From: matthias.vogelgesang at gmail.com (Matthias Vogelgesang) Date: Sat, 23 Feb 2008 06:43:59 -0800 (PST) Subject: Getting stdout from other processes References: <7d2d1344-49cf-476f-9408-e9e53516c899@71g2000hse.googlegroups.com> <deff836f-26fe-4230-8b61-106f2f15ec0d@28g2000hsw.googlegroups.com> Message-ID: <37b273bf-3f4f-409f-bb19-03b03505d2e7@n58g2000hsf.googlegroups.com> Hi, Miki wrote: > The current "official" module to use is subprocess (pipe = > Popen([client], stdout=PIPE)) > However if the client is sending data, reading from the pipe.stdout > will block the server. > If you *need* to wait, then you can use pipe.wait(), otherwise do as > Diez suggested and have a thread > read the client output and propagate it to the main loop (maybe using > Queue.Queue) Thanks both of you for your explanations. In fact, it did the trick. -- Matthias From R.Brodie at rl.ac.uk Wed Feb 27 11:18:53 2008 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Wed, 27 Feb 2008 16:18:53 -0000 Subject: XML expat error References: <babb6775-311d-4f7a-bc03-90f249e34180@s19g2000prg.googlegroups.com> Message-ID: <fq42hd$loe$1@south.jnrs.ja.net> "dirkheld" <dirkheld at gmail.com> wrote in message news:babb6775-311d-4f7a-bc03-90f249e34180 at s19g2000prg.googlegroups.com... > xml.parsers.expat.ExpatError: not well-formed (invalid token): line > 554, column 20 > > I guess that the element I try to read or the XML(which would be > strange since they have been created with the same code) can't ben > retrieved. It's fairly easy to write non-robust XML generating code, and also quick to test if one file is always bad. Drop it into a text editor or Firefox, and take a quick look at line 554. Most likely some random control character has sneaked in; it only takes (for example) one NUL to make the document ill-formed. From http Fri Feb 22 13:39:31 2008 From: http (Paul Rubin) Date: 22 Feb 2008 10:39:31 -0800 Subject: Article of interest: Python pros/cons for the enterprise References: <e5ae7c80-8bb7-4903-92ff-89e4f62c0239@b29g2000hsa.googlegroups.com> <2f1527a7-2f66-44c7-9665-4d8ff01fa5ab@28g2000hsw.googlegroups.com> <47bd4a24$0$25225$426a74cc@news.free.fr> <f9547b0a-bffa-44b3-8638-12b1dd88fe49@p43g2000hsc.googlegroups.com> <mailman.1057.1203605188.9267.python-list@python.org> <036e93e6-5840-4a3c-8642-67a0a9ec44f2@i7g2000prf.googlegroups.com> <ae0cf9a7-842d-4edf-bd1a-bf4057a694c5@q70g2000hsb.googlegroups.com> <784ec210-f389-4a15-b458-961100de9103@v3g2000hsc.googlegroups.com> <ca9a03a4-ab5e-4e0f-92e4-4982386d7a8e@d5g2000hsc.googlegroups.com> <5MSdncqVGdEXiSPanZ2dnUVZ_vPinZ2d@comcast.com> <b821608f-835b-4f09-95e2-76c8cb405b9e@j28g2000hsj.googlegroups.com> <7xskzldz7l.fsf@ruckus.brouhaha.com> <a88eef80-1b0a-4e09-ae46-9fa632bc1d2e@71g2000hse.googlegroups.com> <roy-22EDAB.09254722022008@70-1-84-166.area1.spcsdns.net> <fbefd378-369b-4d8d-ae27-40d7aa47b036@d21g2000prf.googlegroups.com> Message-ID: <7xhcg025uk.fsf@ruckus.brouhaha.com> Nicola Musatti <nicola.musatti at gmail.com> writes: > > Partial guarantees are like being a little bit pregnant. > > Yes, and I'm sure your tests cover all possible paths through your code. That is the point of type checking. With a sound type system, "int x" makes sure, at compile time, that x stays an integer through every possible path through the code and never becomes a string or anything like that. That's why Pierce's book on type systems describes them as "lightweight formal methods". The happening thing in language research these days is designing more and more powerful type systems so that you can make sure, at compile time, that any predicate that you can describe mathematically remains true through all possible paths through the code. So you can have the compiler make sure, through every possible path through the code, not just that x is some integer, but is the actual integer that you want, e.g. if you want x to be the largest prime number smaller than 3*y, you can define a type for that, and then if your program to compute x passes the type checker, it cannot compute the wrong value. Python is a very pleasant and productive environment for banging out code quickly that does practical things straightforwardly, but in some ways it feels almost like assembly language, in that you have to keep track in your head of what types of values your program is computing, instead of being able to rely on the compiler to catch errors. From mwilson at the-wire.com Sun Feb 24 19:09:44 2008 From: mwilson at the-wire.com (Mel) Date: Sun, 24 Feb 2008 19:09:44 -0500 Subject: How about adding rational fraction to Python? References: <b2b884df-b499-4740-9d21-cae87bbd790d@q77g2000hsh.googlegroups.com> <K_adnYlVJrhd9SranZ2dnUVZ_iydnZ2d@comcast.com> <dde6d718-fb7d-4bce-a1da-5e78c744cf69@72g2000hsu.googlegroups.com> <naidnRHl24M8GCranZ2dnUVZ_vHinZ2d@comcast.com> <70ecaf16-7308-455f-9048-730b2b2f9f2f@p43g2000hsc.googlegroups.com> <13rf9tvbkt66r2a@corp.supernews.com> <198927a7-9478-42b3-a972-82049f0130ac@u10g2000prn.googlegroups.com> <1bc9bba7-dc7f-4cfe-8e1c-fa5901c9f556@n77g2000hse.googlegroups.com> <97f30679-483d-4751-9a6e-0858b36eb426@d4g2000prg.googlegroups.com> <mailman.1169.1203875215.9267.python-list@python.org> <f4443376-04a0-414e-9eba-149bf9779bef@34g2000hsz.googlegroups.com> <649ac8a9-ae09-4e9b-85c2-f37043af21fd@28g2000hsw.googlegroups.com> <edd61692-2b00-405c-adfe-7f5224097e95@e10g2000prf.googlegroups.com> <ead37b53-5174-4a54-ae36-f0e1be1dd065@z17g2000hsg.googlegroups.com> Message-ID: <fpt11h$uob$1@aioe.org> Mensanator wrote: > On Feb 24, 1:09?pm, Lie <Lie.1... at gmail.com> wrote: >> I decided to keep the num/den limit low (10) because higher values >> might obscure the fact that it do have limits. [ ... ] > > Out of curiosity, of what use is denominator limits? > > The problems where I've had to use rationals have > never afforded me such luxury, so I don't see what > your point is. In calculations dealing only with selected units of measure: dollars and cents, pounds, ounces and tons, teaspoons, gallons, beer bottles 28 to a case, then the denominators would settle out pretty quickly. In general mathematics, not. I think that might be the point. Mel. From stefan_ml at behnel.de Wed Feb 13 16:09:25 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 13 Feb 2008 22:09:25 +0100 Subject: Write ooxml .ods (spreadsheat) from python? In-Reply-To: <mailman.737.1202926949.9267.python-list@python.org> References: <fousj4$lsn$1@ger.gmane.org> <47B32503.5000008@rolfvandekrol.nl> <mailman.737.1202926949.9267.python-list@python.org> Message-ID: <47B35C85.7010206@behnel.de> Neal Becker wrote: > # OOo's libraries > import uno > > IIUC, this is the same problem. This uno module is tied to an old python > (2.2?) that ships with OO. Is it available standalone to build for python > 2.5? Roll your own OpenOffice server: http://pypi.python.org/pypi/z3c.recipe.openoffice Stefan From galaviel at yahoo.com Thu Feb 28 03:47:07 2008 From: galaviel at yahoo.com (Gal Aviel) Date: Thu, 28 Feb 2008 08:47:07 +0000 (UTC) Subject: threading/Queue: join() and =?utf-8?b?dGFza19kb25lKCk=?= not working? (deadlock) References: <mailman.1360.1204139707.9267.python-list@python.org> <3f0d376e-693d-4cff-907e-e935a26fec62@60g2000hsy.googlegroups.com> Message-ID: <loom.20080228T084622-971@post.gmane.org> 7stud <bbxx789_05ss <at> yahoo.com> writes: > What is task_done()? The python docs don't list any such function. I'm using Python 2.5 and it's in the docs ... From azam.farooq3 at gmail.com Mon Feb 4 06:34:05 2008 From: azam.farooq3 at gmail.com (Farooq) Date: Mon, 4 Feb 2008 03:34:05 -0800 (PST) Subject: Need Smart Phone with new features? please click here Message-ID: <d91bdfec-0b88-4865-a7a9-72a3d56f1641@l16g2000hsh.googlegroups.com> www.enmac.com.hk GSM Mobile Phones, Digital iPods, Digital Clocks, Digital Pens, Digital Quran. Enjoy these products with Islamic Features (Complete Holy Quran with Text and Audio, Tafaseer books, Ahadees Books, Daily Supplications, Universal Qibla Direction, Prayer Timing and much more) visit our website for more information. From emailamit at gmail.com Thu Feb 7 13:38:39 2008 From: emailamit at gmail.com (Amit Gupta) Date: Thu, 7 Feb 2008 10:38:39 -0800 (PST) Subject: re question Message-ID: <8d6f4d80-d979-4baf-925e-b6cd1daed79d@s19g2000prg.googlegroups.com> Python'ites I searched around "google" to find the answer to this question, but I can't: I have a named regexp : x = re.compile("(?P<me>[a-z]+)") What I want is an iterator, that can return me both the "groupname" and the matched string, e.g: m = x.search("aa") Somehow, I want to get {"me" : "aa"}, either as dictionary or some iterable form. All I found is, I need to know the "groupname" to get the corresponding match. Any help is appreciated. A From steve at holdenweb.com Thu Feb 21 15:19:08 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 21 Feb 2008 15:19:08 -0500 Subject: can't set attributes of built-in/extension type In-Reply-To: <fpkhb4$56e$1@ger.gmane.org> References: <mailman.1074.1203617977.9267.python-list@python.org> <b109fee5-5864-4bc8-81a3-1c183a8d3bf5@60g2000hsy.googlegroups.com> <fpkhb4$56e$1@ger.gmane.org> Message-ID: <fpkmbu$1e4$1@ger.gmane.org> Neal Becker wrote: > 7stud wrote: > >> On Feb 21, 11:19 am, Neal Becker <ndbeck... at gmail.com> wrote: >>> I'm working on a simple extension. Following the classic 'noddy' >>> example. >>> >>> In [15]: cmplx_int32 >>> Out[15]: <type 'numpy.cmplx_int32'> >>> >>> Now I want to add an attribute to this type. More precisely, I want a >>> class attribute. >>> >>> cmplx_int32.test = 0 >>> --------------------------------------------------------------------------- >>> TypeError Traceback (most recent call >>> last) >>> >>> /home/nbecker/numpy/<ipython console> in <module>() >>> >>> TypeError: can't set attributes of built-in/extension >>> type 'numpy.cmplx_int32' >>> >>> What am I missing? >> >> class Dog(object): >> def __setattr__(self, attr, val): >> print "TypeError: can't set attributes of built-in/extension" >> print "type 'Dog.cmplx_int32'" >> >> d = Dog() >> d.test = 0 >> >> --output:-- >> TypeError: can't set attributes of built-in/extension >> type 'Dog.cmplx_int32' > > Not quite, I'm setting a class attribute, not an attribute on an instance. > Quite. The problem is that extension types' attributes are determined by the layout of the object's slots and forever fixed in the C code that implements them: the slots can't be extended, so there's no way to add attributes. This is an efficiency feature: it would be *extremely* slow to look up the basic types' attributes using late-binding (it would also change the nature of the language somewhat, making it more like Ruby or Self). So the reason you can't do what you want to is the same reason why you can't add attribute to the built-in types (which are, of course, clearly mentioned in the error message). >>> object.anyoldname = "You lose!" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can't set attributes of built-in/extension type 'object' >>> If you look in typeobject.c you'll find this error message occurs when the object's type isn't a PyHeapTypeObject (in other words, if it's one of the built-in or extension types). regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From mc_i2020 at yahoo.co.in Wed Feb 13 11:01:11 2008 From: mc_i2020 at yahoo.co.in (Mani Chandra) Date: Wed, 13 Feb 2008 21:31:11 +0530 (IST) Subject: Fw: error in importing scipy Message-ID: <554147.8370.qm@web94604.mail.in2.yahoo.com> --- On Wed, 13/2/08, Mani Chandra <mc_i2020 at yahoo.co.in> wrote: > From: Mani Chandra <mc_i2020 at yahoo.co.in> > Subject: error in importing scipy > To: python-list2 at python.org > Date: Wednesday, 13 February, 2008, 9:30 PM > Hi > I get the following error while importing scipy. > /usr/local/lib/python2.4/site-packages/scipy_base/__init__.py:16: > RuntimeWarning: Python C API version mismatch for module > fastumath: This Python has API version 1013, module > fastumath has version 1012. import fastumath # no need to > use scipy_base.fastumath > > Can someone please help me out? > > Thanks, > Mani chandra > > > Get the freedom to save as many mails as you wish. To > know how, go to > http://help.yahoo.com/l/in/yahoo/mail/yahoomail/tools/tools-08.html Unlimited freedom, unlimited storage. Get it now, on http://help.yahoo.com/l/in/yahoo/mail/yahoomail/tools/tools-08.html/ From gagsl-py2 at yahoo.com.ar Thu Feb 28 11:15:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 28 Feb 2008 14:15:14 -0200 Subject: Python's BNF References: <85ae78f6-056b-4219-9952-66750e3ebf58@e60g2000hsh.googlegroups.com> <mailman.1373.1204150177.9267.python-list@python.org> <d8b1a179-cbd5-4c12-a5e8-f34ce9574a24@i12g2000prf.googlegroups.com> Message-ID: <op.t68srolrx6zn5v@a98gizw.cpe.telecentro.net.ar> En Thu, 28 Feb 2008 12:33:33 -0200, <MartinRinehart at gmail.com> escribi?: > Implemented all your suggestions, with two exceptions. > > Changed file read to readlines(), but not open(...).readlines(). I > love to say file.close(). Gives me a feeling of security. (We could > discuss RAM waste v. I/O speed but this input file is just 10KB, so > neither matters.) Ok, what about this? with open(...) as f: for line in f: ...do something with each line... The with statement guarantees that close (implicit) is always called. > Removed one of the three globals, but left the other two. Couldn't see > any real advantage to passing poor 'ofile' from hand to hand > (writeHTML() to writeBody() to writeEntries() ...) as opposed to > letting him rest easy in his chair, doing a little writing when > called. Perhaps not in this small script, but as a design principle, having a global `ofile` object doesn't look good... > Also changed the opening doc comment to give you appropriate credit. No need for that. -- Gabriel Genellina From steve at holdenweb.com Sun Feb 24 08:39:22 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 24 Feb 2008 08:39:22 -0500 Subject: advanced usage of python threads In-Reply-To: <47C055DF.3090102@nerdshack.com> References: <47C055DF.3090102@nerdshack.com> Message-ID: <fprs2q$rg6$1@ger.gmane.org> hyperboreean wrote: > Chris, I have already made my choice, I am asking just for a little help > with some documentation. > I know about twisted.enterprise.adbapi, but the company is working with > sqlalchemy at the time. > So please, I know you have good intentions but you're kind of not > helping me :) > Well, probably instead of asking you people I should just start > searching the net, thing that I am already doing. But if any of you has > some info, please share. > > Thanks. > Well, if you plan to use threading with Twisted you would probably be a lot better off asking questions on the Twisted mailing list. twisted-python at twistedmatrix.com regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From rocksportrocker at googlemail.com Wed Feb 27 07:34:44 2008 From: rocksportrocker at googlemail.com (rocksportrocker) Date: Wed, 27 Feb 2008 04:34:44 -0800 (PST) Subject: BaseHTTPServer and do_POST method References: <6fa9fbde-fc6b-4b4a-a8ec-33bb504b74a5@62g2000hsn.googlegroups.com> Message-ID: <b303de65-8f11-4e2a-8dc6-7703db4f7a39@n75g2000hsh.googlegroups.com> On Feb 27, 1:28 pm, rocksportrocker <rocksportroc... at googlemail.com> wrote: > Hi, > > I am trying to implement a local server for storing and retrieving > numerical data. > So I used BaseHTTPServer as follows: > > from BaseHTTPServer import * > > class Handler(BaseHTTPRequestHandler): > > def do_POST(self): > > print "POST" > self.send_response(200) > > httpd = HTTPServer(("",8000), Handler) Please ignore this post, I accidentally hit the "Send" button before finishing. Greetings, Uwe From python.list at tim.thechases.com Wed Feb 27 11:23:49 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 27 Feb 2008 10:23:49 -0600 Subject: Making string-formatting smarter by handling generators? Message-ID: <47C58E95.1030000@tim.thechases.com> Is there an easy way to make string-formatting smart enough to gracefully handle iterators/generators? E.g. transform = lambda s: s.upper() pair = ('hello', 'world') print "%s, %s" % pair # works print "%s, %s" % map(transform, pair) # fails with a """ TypeError: not enough arguments for format string """ I can force it by wrapping the results of my generator in a call to tuple() or list() print "%s, %s" % tuple(map(transform, pair)) but it feels a bit hackish to me. I find I hit it mostly with calls to map() where I want to apply some transform (as above) to all the items in a list of parameters such as "%s=%s&%s=%s" % map(urllib.quote, params) Any suggestions? (even if it's just "get over your hangup with wrapping the results in list()/tuple()" :) Thanks, -tkc From http Fri Feb 22 17:31:06 2008 From: http (Paul Rubin) Date: 22 Feb 2008 14:31:06 -0800 Subject: ANN: NUCULAR B3 Full text indexing (now on Win32 too) References: <8e155507-f487-40d6-96e3-7aaa8f431fcd@e23g2000prf.googlegroups.com> <7xir0smw44.fsf@ruckus.brouhaha.com> <fp0saf$lt0$1@atlantis.news.tpi.pl> <7xir0sq87q.fsf@ruckus.brouhaha.com> <069f8a1c-fe20-41c2-95e4-e8219acb00a1@d5g2000hsc.googlegroups.com> Message-ID: <7xoda87hed.fsf@ruckus.brouhaha.com> Aaron Watters <aaron.watters at gmail.com> writes: > [apologies to the list: I would have done this offline, > but I can't figure out Paul's email address.] > > 1) Paul please forward your email address Will send it privately. I don't have a public email address any more (death to spam!!!). My general purpose online contact point is http://paulrubin.com which currently has an expired certificate that I'll get around to renewing someday. Meanwhile you have to click "accept" to connect using the expired cert. > 3) Since you seem to know about these things: I was thinking > of adding an optional feature to Nucular which would allow > a look-up like "given a word find all attributes that contain > that word anywhere and give a count of the number of times it > is found in that attribute as well as the entry id for an example > instance (arbitrarily chosen). I was thinking about calling > this "inverted faceting", but you probably know a > better/standard name, yes? What is it please? Thanks! > Answers from anyone else welcomed also. In Solr this is called the DisMax (disjunction maximum) handler, I think. I tried it and it doesn't work very well, and ended up using a script written by a co-worker, that expands such queries to more complex queries that put user-supplied weights on each field. It is a somewhat messy problem. Otis Gospodnetic's book "Lucene in Action" talks about it some, I believe. Manning and Schutz are working on a new book at http://informationretrieval.org that discusses fancier methods. I think these are worth looking into, but I haven't had the bandwidth to spend time on it so far. From jeff at schwabcenter.com Mon Feb 18 19:12:24 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Mon, 18 Feb 2008 16:12:24 -0800 Subject: Passing a callable object to Thread In-Reply-To: <7xr6f9rf10.fsf@ruckus.brouhaha.com> References: <52465ed8-7d25-40ca-be69-478b308af879@u10g2000prn.googlegroups.com> <7xir0psq9l.fsf@ruckus.brouhaha.com> <452d63ea-3373-4393-9c28-38116f96d2e9@u10g2000prn.googlegroups.com> <mailman.843.1203131001.9267.python-list@python.org> <7xzlu1bmdj.fsf@ruckus.brouhaha.com> <mailman.846.1203134004.9267.python-list@python.org> <h6SdnbMFFusl8ivanZ2dnUVZ_jCdnZ2d@comcast.com> <7x3artbhwl.fsf@ruckus.brouhaha.com> <zO-dnfnEyInh6SvanZ2dnUVZ_i2dnZ2d@comcast.com> <c0c703ae-b1f6-434d-b37c-edcbca3a03e7@s8g2000prg.googlegroups.com> <luidnTNq6NxxmCfanZ2dnUVZ_jOdnZ2d@comcast.com> <ad3a39bb-5f93-4025-97c7-419b89ce0fb6@d4g2000prg.googlegroups.com> <V4qdnctmqr7LjifanZ2dnUVZ_hadnZ2d@comcast.com> <7xr6f9rf10.fsf@ruckus.brouhaha.com> Message-ID: <T9WdnTk1FqVZgyfanZ2dnUVZ_tijnZ2d@comcast.com> Paul Rubin wrote: > Jeff Schwab <jeff at schwabcenter.com> writes: >>>> In CS, a tuple is a kind of data structure that is specifically not >>>> identical with any of its elements. That's the sort of tuple used in >>>> Python. > > The usual CS meaning of "tuple" is more like the physics meaning than > like the Python meaning, I think. That has not been my experience. >>>>>> (a,) is (a,) >>> False >> The tuple on the left is not identical with the tuple on the right, >> even though they are equivalent. > > Implementation artifact. It could be constant folded. > x = (a,) > y = x > x is y > should print True. I gave a similar example, but you snipped it. >> An interesting thing about Python is that numbers of built-in types >> are flyweights. Unlike literals of non-flyweight types, distinct >> instances of a given numeric literal actually refer to the same object: >> >> >>> 5 is 5 >> True >> >>> 999999999999999999999999999999 is 999999999999999999999999999999 >> True >> >>> 3.5 is 3.5 >> True > > Again an implementation artifact, not guaranteed by the language. Try: > (5+1) is (5+1) True > then try > (999999999999999999999999999999+1) is (999999999999999999999999999999+1) False I think you're a little confused about the meaning of "numeric literal." (5+1) is not a numeric literal. Neither is (999999999999999999999999999999+1). The flyweight pattern does not guarantee that all equivalent instances of an object type will be identical. Maybe I should have said that *some* distinct instances of a given numeric literal actually refer to the same object, so as not to imply that *all* of them did. I don't know whether 5 is always guaranteed to be the same object as any other 5 in a given Python session. From makkalot at gmail.com Sat Feb 16 04:04:26 2008 From: makkalot at gmail.com (makkalot at gmail.com) Date: Sat, 16 Feb 2008 11:04:26 +0200 Subject: Inter-process communication, how? Part 2 In-Reply-To: <7388a760-7c3d-47bf-9f59-15acf6547dde@n20g2000hsh.googlegroups.com> References: <7388a760-7c3d-47bf-9f59-15acf6547dde@n20g2000hsh.googlegroups.com> Message-ID: <200802161104.27200.makkalot@gmail.com> Sunday 23 December 2007 Tarihinde 03:56:05 yazm??t?: > Hello, > > just to recap: last time I asked how to do an interprocess > communitation, between one Manager process (graphical beckend) and > some Worker processes. Why just dont use dbus , and then have a drink :) From agenkin at gmail.com Thu Feb 7 10:29:55 2008 From: agenkin at gmail.com (agenkin at gmail.com) Date: Thu, 7 Feb 2008 07:29:55 -0800 (PST) Subject: Looking for library to estimate likeness of two strings References: <86e63d06-124e-49e8-82e2-dfbea01fcce7@v17g2000hsa.googlegroups.com> <mailman.428.1202369868.9267.python-list@python.org> Message-ID: <38730101-450c-4c1c-8ef1-70660dc7ef4e@k39g2000hsf.googlegroups.com> On Feb 7, 2:37 am, "Daniel Fetchinson" <fetchin... at googlemail.com> wrote: > Hi folks, just went through this thread and a related one from 2006 > and I was wondering what the best solution is for using these string > metrics in a database search. If I want to query the database for a > string or something that is close to it (close being defined by one of > the string metrics discussed above) it seems I have to select each and > every word from the database and compare it with the query word which > is very ineffective. I have never used sqlite database, but Postgres has a module that implements levenshtein(), soundex() and metaphone() functions, so you can do something like this: SELECT * FROM s WHERE soundex(name) = soundex('john'); SELECT * FROM s WHERE difference(name, 'john') > 2; http://www.postgresql.org/docs/8.3/static/fuzzystrmatch.html From dave_mikesell at fastmail.fm Fri Feb 29 08:15:04 2008 From: dave_mikesell at fastmail.fm (dave_mikesell at fastmail.fm) Date: Fri, 29 Feb 2008 05:15:04 -0800 (PST) Subject: Python app at startup! References: <fq7equ$nl3$1@ss408.t-com.hr> Message-ID: <5fd991f2-d079-4218-8198-fa79c2d29955@z17g2000hsg.googlegroups.com> On Feb 28, 5:07 pm, "SMALLp" <po... at email.t-com.hr> wrote: > Hy. I create simple application. Yust an windows and "compile" it with > py2exe. I add registry value > reg add HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /v > MyApp /t REG_SZ /d C:\myapp.exe /f' > > And it wont start. When i use console instead od window in py2exe i get > console opend but it closes. Does it do the same thing when you run it with the Python interpreter? From python.list at tim.thechases.com Mon Feb 11 16:02:31 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 11 Feb 2008 15:02:31 -0600 Subject: Better way to do this? In-Reply-To: <f32fb764-2b29-44a8-963b-f0ca625a5cd5@e25g2000prg.googlegroups.com> References: <f32fb764-2b29-44a8-963b-f0ca625a5cd5@e25g2000prg.googlegroups.com> Message-ID: <47B0B7E7.4080000@tim.thechases.com> > I have a tuple of tuples, in the form--> ((code1, 'string1'),(code2, > 'string2'),(code3, 'string3'),) > > Codes are unique. A dict would probably be the best approach but this > is beyond my control. > > Here is an example: >>>> pets = ((0,'cat'),(1,'dog'),(2,'mouse')) > > If I am given a value for the code I need to retrieve the string > representation. The value is guaranteed to be valid. > > This is what I came up with... > >>>> value=1 >>>> [ pet for code, pet in pets if value==code ][0] > 'dog' Does anything prevent you from writing that as >>> dict(pets)[value] 'dog' ? -tkc From marek.rocki at wp.pl Tue Feb 26 11:46:18 2008 From: marek.rocki at wp.pl (marek.rocki at wp.pl) Date: Tue, 26 Feb 2008 08:46:18 -0800 (PST) Subject: dict.get and str.xsplit References: <98a989a2-dfcb-4da5-979a-12011d5e4f8e@i12g2000prf.googlegroups.com> <62il6uF223i2qU1@mid.uni-berlin.de> <b8a2a59c-621a-46bc-b84b-f59d9f010273@e10g2000prf.googlegroups.com> <d690d982-cd4e-4622-8c7c-98baf1671bdb@d5g2000hsc.googlegroups.com> <40f0527b-6308-4394-a7e9-2abd282e407f@k2g2000hse.googlegroups.com> Message-ID: <a04f15c3-e7d8-478f-925f-822d5444e65d@e25g2000prg.googlegroups.com> bearophileH... at lycos.com napisa?(a): > marek.ro... at wp.pl: > > As for the original prooblem, why not use > > defaultdict? I think it's the most idiomatic way to achieve what we > > want. And also the fastest one, according to my quick-and-dirty tests: > > It adds the new keys, I can't accept that: Right, my fault not noticing that. I experimented further with __missing__ method and with "ask forgiveness" idiom (try... except KeyError) and they were both noticeably slower. So checking with "in" may be the most efficient way we have. Regards, Marek From jorge.vargas at gmail.com Wed Feb 20 08:12:23 2008 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Wed, 20 Feb 2008 07:12:23 -0600 Subject: is this data structure build-in or I'll have to write my own class? Message-ID: <32822fe60802200512udfedb04j6df18dfa7ef55900@mail.gmail.com> I need a data structure that will let me do: - attribute access (or index) - maintain the order (for iter and print) - be mutable. in case there isn't one. I was thinking having a base class like Bunch http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308 and on top of that keeping a list of the keys and pop/push to the list when adding/deleting items. I don't like this idea because I'll have to keep each key twice. (in the list and in __dict__, is this the only way of doing it? From gagsl-py2 at yahoo.com.ar Thu Feb 14 17:06:43 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 14 Feb 2008 20:06:43 -0200 Subject: How to tell if I'm being run from a shell or a module References: <44e07112-e3f5-4446-8522-24c2476efd4a@e10g2000prf.googlegroups.com> <a8b5d278-a455-4eb3-a513-c5bf4deafa2c@q78g2000hsh.googlegroups.com> <9ec4f650-38bb-43e6-a78e-e0b4f1b658dc@e6g2000prf.googlegroups.com> Message-ID: <op.t6jbphbcx6zn5v@gabriel2.softlabbsas.com.ar> En Thu, 14 Feb 2008 19:09:10 -0200, <dg.google.groups at thesamovar.net> escribi?: > Thanks for the replies, but it's not what I meant. What I want to be > able to determine is whether or not the user is running from an > interactive shell (like IPython or IDLE). Checking if > __name__=='__main__' checks if the current module is the one being > run, but suppose you have two modules A and B, with the function f > defined in module B that should print 'Interactive' or 'Module' say. > The module A just consists of: import B; B.f(). Now whenever f is > called, __name__ will not be '__main__' for it. Someone using IDLE > could write import B then B.f() too. The question is: is there a way > for f to determine if someone was using an interactive shell to call > it or if it was being called some other way. The way I came up with > works in these limited cases but won't work in a more general > situation (but perhaps there is no way for it to know in the more > general situation). It depends on what you mean by "an interactive shell"? If you start your script with: python -i whatever.py is it an interactive shell or not? I tried these two criteria: a) See if the __main__ module has a __file__ attribute. b) See if sys.stdin is a real tty These are the results I got on Windows for several configurations: <test.py> import sys print "__main__ has __file__", hasattr(sys.modules['__main__'], '__file__') import os print "sys.stdin is a tty", hasattr(sys.stdin, "fileno") and os.isatty(sys.stdin.fileno()) </test.py> python test.py __main__ has __file__ True sys.stdin is a tty True python -i test.py __main__ has __file__ True sys.stdin is a tty True python test.py <nul >nul __main__ has __file__ True sys.stdin is a tty True python test.py <emptyfile >nul __main__ has __file__ True sys.stdin is a tty False pythonw.exe (the consoleless Python executable for Windows) __main__ has __file__ True sys.stdin is a tty False IDLE __main__ has __file__ False sys.stdin is a tty False pythonwin.exe __main__ has __file__ False sys.stdin is a tty False -- Gabriel Genellina From vaneric001 at gmail.com Tue Feb 19 01:01:04 2008 From: vaneric001 at gmail.com (vaneric) Date: Mon, 18 Feb 2008 22:01:04 -0800 (PST) Subject: average of PIL images References: <eefc000d-a8da-4e55-a501-cabd0f099a76@e10g2000prf.googlegroups.com> <mailman.929.1203367112.9267.python-list@python.org> Message-ID: <de943c72-6b98-4143-af9b-a72768c7a261@e23g2000prf.googlegroups.com> On Feb 19, 1:38 am, Robert Kern <robert.k... at gmail.com> wrote: >Averaging color > images is tricky; you really shouldn't do it in the RGB colorspace. hi, thanx for the guidance and detailed replies..I tried to pack the r,g,b into a single value like below(something a member posted in the past) def rgbTopixelvalue((r,g,b)): alpha=255 return unpack("l", pack("BBBB", b, g, r, alpha))[0] if i apply this for all images i can represent each image as an array of longs instead of tuples.then for a pixel i can calculate the average value after this if i do the casting as you advised and create the avg image avgface = avgface.astype(numpy.uint8) here if i use these pixelvalues to create an imag img =Image.fromstring('RGB', (width, height), avgface.tostring()) it will fail because of -'not enough image data'..is there an alternative to create average rgb color image ?(i want to keep the rgb so can't convert to greyscale) is there something wrong with my approach? I am a newbie in PIL/ imageprocessing ..so i would greately appreciate feedback eric From stef.mientki at gmail.com Sun Feb 17 14:50:38 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sun, 17 Feb 2008 20:50:38 +0100 Subject: pyinstall and matplotlib In-Reply-To: <f2a09050-c924-4605-bd47-f32715ccfe98@i29g2000prf.googlegroups.com> References: <254161cb-f927-4659-b1a5-c34b5c2953ac@s8g2000prg.googlegroups.com> <3144e444-3542-4550-a280-ff15da8bed0b@l16g2000hsh.googlegroups.com> <rowen-A8050A.10072913022008@news.u.washington.edu> <9d85cb45-2e62-4c4a-9d31-35e5cb9ef3ea@1g2000hsl.googlegroups.com> <f2a09050-c924-4605-bd47-f32715ccfe98@i29g2000prf.googlegroups.com> Message-ID: <47B8900E.5000206@gmail.com> hi John, John Henry wrote: > Anybody willing to help? > I struggled the past few days with the same problem, and with the help of Werner Bruhin (wxPython list) I found a solution. I had 2 problems: - not finding mpl datapath - matplotlib insisted on installing backends that were distorted on my system The first problem was solved with the following script: it has some special parts - remove the distro and build directories before running setup - a special matplot part, ensuring mpl-data is copied and installed - a lot of excludes for matplotlib ( which doesn't seem to work :-( ) Kill_Distro = True MatPlotLib_Wanted = True from distutils.core import setup import py2exe import sys subdirs = [ '..\\P24_support', '..\\P24_pictures', '..\\P24_Lib_Extensions' ] for subdir in subdirs: if not ( subdir in sys.path) : sys.path.append ( subdir ) from file_support import * import shutil import glob # *********************************************************************** # Some suggests that old build/dist should be cleared # *********************************************************************** dist_paths = [ 'D:\\Data_Python\\P24_PyLab_Works\\build', 'D:\\Data_Python\\P24_PyLab_Works\\dist' ] for path in dist_paths : if File_Exists ( path ) : shutil.rmtree ( path ) # *********************************************************************** # *********************************************************************** # *********************************************************************** data_files = [] packages = [] includes = [] excludes = [] dll_excludes = [] data_files.append ( ( '', glob.glob ( 'templates_*.*' ) ) ) # *********************************************************************** # For MatPlotLib # *********************************************************************** if MatPlotLib_Wanted : import matplotlib includes.append ( 'matplotlib.numerix.random_array' ) packages.append ( 'matplotlib' ) packages.append ( 'pytz' ) data_files.append ( ( r'mpl-data', glob.glob ( r'P:\\Python\\Lib\\site-packages\\matplotlib\\mpl-data\\*.*' ))) data_files.append ( ( r'mpl-data', glob.glob ( r'P:\\Python\\Lib\\site-packages\\matplotlib\\mpl-data\\matplotlibrc' ))) data_files.append ( ( r'mpl-data\\images', glob.glob ( r'P:\\Python\\Lib\\site-packages\\matplotlib\\mpl-data\\images\\*.*' ))) data_files.append ( ( r'mpl-data\\fonts\\afm', glob.glob ( r'P:\\Python\\Lib\\site-packages\\matplotlib\\mpl-data\\fonts\\afm\\*.*' ))) data_files.append ( ( r'mpl-data\\fonts\\pdfcorefonts', glob.glob ( r'P:\\Python\\Lib\\site-packages\\matplotlib\\mpl-data\\fonts\\pdfcorefonts\\*.*' ))) data_files.append ( ( r'mpl-data\\fonts\\ttf', glob.glob ( r'P:\\Python\\Lib\\site-packages\\matplotlib\\mpl-data\\fonts\\ttf\\*.*' ))) excludes.append ( '_gtkagg') excludes.append ( '_tkagg' ) excludes.append ( '_agg2' ) excludes.append ( '_cairo' ) excludes.append ( '_cocoaagg' ) excludes.append ( '_fltkagg' ) excludes.append ( '_gtk' ) excludes.append ( '_gtkcairo') excludes.append ( 'backend_qt' ) excludes.append ( 'backend_qt4') excludes.append ( 'backend_qt4agg' ) excludes.append ( 'backend_qtagg' ) excludes.append ( 'backend_cairo' ) excludes.append ( 'backend_cocoaagg' ) excludes.append ( 'Tkconstants' ) excludes.append ( 'Tkinter' ) excludes.append ( 'tcl' ) excludes.append ( "_imagingtk" ) excludes.append ( "PIL._imagingtk" ) excludes.append ( "ImageTk" ) excludes.append ( "PIL.ImageTk" ) excludes.append ( "FixTk" ) dll_excludes.append ( 'libgdk-win32-2.0-0.dll' ) dll_excludes.append ( 'libgdk_pixbuf-2.0-0.dll' ) dll_excludes.append ( 'libgobject-2.0-0.dll') dll_excludes.append ( 'tcl84.dll' ) dll_excludes.append ( 'tk84.dll' ) dll_excludes.append ( 'tclpip84.dll' ) # *********************************************************************** # seems not to be found (imported in brick.py) includes.append ( 'PyLab_Works_properties' ) # *********************************************************************** # *********************************************************************** # If run without args, build executables, in quiet mode. if len(sys.argv) == 1: sys.argv.append("py2exe") setup ( windows = ['PyLab_Works.py'] , options = { 'py2exe' : { 'includes' : includes, 'excludes' : excludes, 'dll_excludes' : dll_excludes, 'packages' : packages, }}, data_files = data_files ) import subprocess result = subprocess.call ( [ 'P:\Program Files\Inno Setup 4\ISCC.exe', 'D:\Data_Python\P24_PyLab_Works\PyLab_Works.iss']) if (result==0) and Kill_Distro : for path in dist_paths : if File_Exists ( path ) : shutil.rmtree ( path ) Th? essential issue is not to use pylab to do the imports for you, but perform your own imports, this might be a lot of work: in my case the import looks like this (I don't include numerix, because I use numpy), so in my program to distribute, I use this : import matplotlib matplotlib.use('WXAgg') from matplotlib.backends.backend_wxagg \ import Toolbar, FigureManager from matplotlib.backends.backend_wxagg \ import FigureCanvasWxAgg as FigureCanvas from matplotlib import rcParams, mlab, cm from matplotlib.mlab import meshgrid from matplotlib.figure import Figure from matplotlib.axes import Subplot hope this might help you somewhat, cheers, Stef From miller.paul.w at gmail.com Sun Feb 3 13:06:04 2008 From: miller.paul.w at gmail.com (miller.paul.w at gmail.com) Date: Sun, 3 Feb 2008 10:06:04 -0800 (PST) Subject: psyco question Message-ID: <2d819b5e-2377-48a3-b1f3-394c1f6f7dda@u10g2000prn.googlegroups.com> Say I have a module with a function f in it, and I do psyco.bind (f) Is there any simple/easy/elegant way to retain a reference to the *unoptimized* version of f so I can call them both and compare performance? I've tried f2 = copy.deepcopy (f) psyco.bind (f) but that doesn't work. Other ways I've thought of that might work just seem silly (like putting the definition of f in a string, using compile() to construct two code objects and using psyco.bind() on one of them), so I'm wondering if there's a good way. Thanks! From http Wed Feb 20 19:42:09 2008 From: http (Paul Rubin) Date: 20 Feb 2008 16:42:09 -0800 Subject: The big shots References: <89d15587-e8de-444c-b240-4a10305146e0@e23g2000prf.googlegroups.com> <3c035ede-d98b-4adc-bde4-5a918bd04dd8@h25g2000hsf.googlegroups.com> <586b3c9c-6b8b-4fce-9307-4984b857276a@s37g2000prg.googlegroups.com> <87ir0jgor9.fsf@benfinney.id.au> Message-ID: <7xlk5f16ou.fsf@ruckus.brouhaha.com> Ben Finney <bignose+hates-spam at benfinney.id.au> writes: > castironpi at gmail.com writes: > > My writing isn't unclear > Please re-assess that statement Really, it may not have been clear at first, but after a while, things became clear. From carsten at uniqsys.com Mon Feb 4 15:02:14 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 04 Feb 2008 15:02:14 -0500 Subject: MySQLdb: commit before cursor close, or after? In-Reply-To: <200802041953.44763.Frank.Aune@broadpark.no> References: <47a75474$0$36368$742ec2ed@news.sonic.net> <200802041953.44763.Frank.Aune@broadpark.no> Message-ID: <1202155334.3466.7.camel@dot.uniqsys.com> On Mon, 2008-02-04 at 19:53 +0100, Frank Aune wrote: > No, you obviously need to commit your changes before closing the cursor. I'm > surprised if your code above even works if adding content to the db. Why is that obvious? Is this some MySQL-specific oddity? In other databases, it's the cursor's execute() method that adds the content to the db (pending a commit of the transaction), and closing the cursor simply means that you are explicitly releasing the resources that the cursor used. Whether the cursor is closed before or after the transaction is committed, or even whether the cursor is explicitly closed at all or not, should make no difference whatsoever. -- Carsten Haese http://informixdb.sourceforge.net From steve at REMOVE-THIS-cybersource.com.au Tue Feb 12 06:59:09 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Tue, 12 Feb 2008 11:59:09 -0000 Subject: Combinatorics References: <forj98$ecf$1@skeeter.ucdavis.edu> <20080212103853.173460f4@outerspace> Message-ID: <13r32gdmr5ieo8f@corp.supernews.com> On Tue, 12 Feb 2008 10:38:53 +0100, pataphor wrote: > On Mon, 11 Feb 2008 23:52:31 -0800 > Michael Robertson <mcrobertson at hotmail.com> wrote: > >> Am I wishing on a star? > > for i in xrange(10**10): > print i > OverflowError: long int too large to convert to int > > The problem seems to be that although python supports arbitrary long > integers, all the internal loop counters still use limited size > integers. I'm curious what you think this has to do with the Original Poster's question, which was about combinatorics (as the subject says), specifically asking where he could find a library to deal with them. -- Steven From inq1ltd at inqvista.com Fri Feb 8 12:10:18 2008 From: inq1ltd at inqvista.com (jim-on-linux) Date: Fri, 08 Feb 2008 12:10:18 -0500 Subject: shelve.open call gives error In-Reply-To: <a02bec49-ee6e-4a4f-9830-33f33761dd47@i7g2000prf.googlegroups.com> References: <a02bec49-ee6e-4a4f-9830-33f33761dd47@i7g2000prf.googlegroups.com> Message-ID: <200802081210.18960.inq1ltd@inqvista.com> On Friday 08 February 2008 03:36, waltbrad wrote: > Working through the Mark Lutz book > Programming Python 3rd Edition. > > A couple of modules in the "Preview" > chapter give me errors. Both on a > shelve.open call: > > Pretty simple code, (2nd example): from; jim-on-linux http://inq1ltd at inqvixta.com My guess, add this and see if it helps > =====code begin===== import dbhash > import shelve > from people import Person, Manager > > bob = Person('Bob Smith', 42, 30000, > 'sweng') sue = Person('Sue Jones', 45, > 40000, 'music') tom = Manager('Tom Doe', > 50, 50000) > > db = shelve.open('class-shelve') > db['bob'] = bob > db['sue'] = sue > db['tom'] = tom > db.close() > ====code end==== > > Error message++++++++ > Traceback (most recent call last): > File "make_db_classes.py", line 9, in > <module> db = shelve.open('class-shelve') > File "C:\PYTHON25\lib\shelve.py", line > 225, in open return > DbfilenameShelf(filename, flag, protocol, > writeback) File > "C:\PYTHON25\lib\shelve.py", line 209, in > __init__ Shelf.__init__(self, > anydbm.open(filename, flag), protocol, > writeback) > File "C:\PYTHON25\lib\anydbm.py", line > 83, in open return mod.open(file, flag, > mode) File "C:\PYTHON25\lib\dbhash.py", > line 16, in open return > bsddb.hashopen(file, flag, mode) File > "C:\PYTHON25\lib\bsddb\__init__.py", line > 306, in hashopen d.open(file, db.DB_HASH, > flags, mode) bsddb.db.DBError: (5, > 'Input/output error') ++++++++++End Error > message > > I've looked on the errata pages of his > website and used Google to find someone > else who ran into this problem. Found > someone else who had a similar error but > no explanation was given. No other reader > of the book seems to have had the problem. > > I'm using 2.5.1 > > I thought maybe the file had to exist > before it could be opened, so I created > one with that name, but no dice. A > different but similar set of errors. I > also thought maybe there had to be a > second argument like 'a', 'r' or 'w'. That > doesn't work either. > > This is the first chapter of the book. > It's an overview of the language features. > So, this is pretty perplexing. Any help > would be appreciated. Thanks. From jorge.vargas at gmail.com Wed Feb 20 08:32:34 2008 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Wed, 20 Feb 2008 07:32:34 -0600 Subject: is this data structure build-in or I'll have to write my own class? In-Reply-To: <fph9bf$45l$1@atlantis.news.tpi.pl> References: <mailman.1016.1203513150.9267.python-list@python.org> <fph9bf$45l$1@atlantis.news.tpi.pl> Message-ID: <32822fe60802200532q3bf21e83j3d0ccb3a388de7bc@mail.gmail.com> 2008/2/20 Jarek Zgoda <jzgoda at o2.usun.pl>: > Jorge Vargas napisa?(a): > > > - attribute access (or index) > > - maintain the order (for iter and print) > > - be mutable. > > These are all attributes of standard Python lists. probably I confused you with the "or index" part. I want to be able to do item.value1 or item['value1'] the list can't do this. > > > in case there isn't one. I was thinking having a base class like Bunch > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308 and on > > top of that keeping a list of the keys and pop/push to the list when > > adding/deleting items. I don't like this idea because I'll have to > > keep each key twice. (in the list and in __dict__, is this the only > > way of doing it? > > What is your objective? From the description of this recipe I cann't get > your use case. > I got an xml object which feed me in data. in a simple format <item> <propety1>foo</propety1> <value1>bar</value1> <propety2>baz</propety2> <value2>bal</value2> </item> I want to turn this into a datastructure I can manipulate in my program for example. >>> print myItem.property1 >>> if myItem.property1[value1] > 0: print 'ok' >>> print myItem {'property1':'value1','property2,'value2'} > -- > Jarek Zgoda > Skype: jzgoda | GTalk: zgoda at jabber.aster.pl | voice: +48228430101 > > "We read Knuth so you don't have to." (Tim Peters) > -- > http://mail.python.org/mailman/listinfo/python-list > From electronixtar at gmail.com Fri Feb 22 01:50:49 2008 From: electronixtar at gmail.com (est) Date: Thu, 21 Feb 2008 22:50:49 -0800 (PST) Subject: n00b with urllib2: How to make it handle cookie automatically? Message-ID: <f5942aa6-b731-4b02-98fd-fbbf05005961@n58g2000hsf.googlegroups.com> Hi all, I need urllib2 do perform series of HTTP requests with cookie from PREVIOUS request(like our browsers usually do ). Many people suggest I use some library(e.g. pycURL) instead but I guess it's good practise for a python beginner to DIY something rather than use existing tools. So my problem is how to expand the urllib2 class from cookielib import CookieJar class SmartRequest(): cj=CookieJar() def __init__(self, strUrl, strContent=None): self.Request = urllib2.Request(strUrl, strContent) self.cj.add_cookie_header(self.Request) self.Response = urllib2.urlopen(Request) self.cj.extract_cookies(self.Response, self.Request) def url def read(self, intCount): return self.Response.read(intCount) def headers(self, strHeaderName): return self.Response.headers[strHeaderName] The code does not work because each time SmartRequest is initiated, object 'cj' is cleared. How to avoid that? The only stupid solution I figured out is use a global CookieJar object. Is there anyway that could handle all this INSIDE the class? I am totally new to OOP & python programming, so could anyone give me some suggestions? Thanks in advance From s.usun.to at informa.i.to.tez.pl Mon Feb 25 09:59:41 2008 From: s.usun.to at informa.i.to.tez.pl (Sebastian Kaliszewski) Date: Mon, 25 Feb 2008 15:59:41 +0100 Subject: Article of interest: Python pros/cons for the enterprise References: <e5ae7c80-8bb7-4903-92ff-89e4f62c0239@b29g2000hsa.googlegroups.com><mailman.1019.1203515892.9267.python-list@python.org><2f1527a7-2f66-44c7-9665-4d8ff01fa5ab@28g2000hsw.googlegroups.com><47bd4a24$0$25225$426a74cc@news.free.fr> <036e93e6-5840-4a3c-8642-67a0a9ec44f2@i7g2000prf.googlegroups.com> <d2777845-6684-4a18-9c8a-e4f58e4e6781@q70g2000hsb.googlegroups.com> <5ae1e7e8-48bc-4919-bd33-72b910c633ee@41g2000hsc.googlegroups.com> <M-6dnav8Iq1ngiLanZ2dnUVZ_tfinZ2d@comcast.com> Message-ID: <fpul2i$nm9$1@bozon2.softax.pl> Jeff Schwab wrote: >> You like managing your own memory, be my guest. But please don't >> imply that you're putting forth less effort because of it. You're >> just putting forth different effort. > > I disagree with you completely. Your points don't make any sense to me > at all. I believe I am putting forth less effort by having a generic > resource-management infrastructure, rather than a memory-specific > language feature -- that's not just an implication, it's my honest belief. Yet your belief is provably wrong. It's been realised by langauge developers long time ago. It's quite simple. 1. Your "generic" resource-management infrastructure is not generic to begin with! It does not work for mutually dependant resources. 2. Your "generic" infrastructure increases burden on the programmer everywhere any resorce (including trivial one like memory) is used, while GC kills that burden in 95% of the cases. C++ish approach puts the notion of ownership everywhere - both in 95% of cases where it's useless and in remaining 5% where it's actually needed. That's not reduced effort by any means. 3. You can't handle clean-up errors in reasonable way in C++ish approach, so anything more complex should not by handled that way anyway. rgds -- "Never underestimate the power of human stupidity" -- L. Lang From aisaac at american.edu Wed Feb 6 14:41:51 2008 From: aisaac at american.edu (Alan G Isaac) Date: Wed, 06 Feb 2008 14:41:51 -0500 Subject: Formatting arrays using myarrayy.tolist() In-Reply-To: <cad605f4-5ee2-461d-a5c4-e6c31847c142@l32g2000hse.googlegroups.com> References: <mailman.392.1202318310.9267.python-list@python.org> <focvko$3no$1@theodyn.ncf.ca> <cad605f4-5ee2-461d-a5c4-e6c31847c142@l32g2000hse.googlegroups.com> Message-ID: <LO6dnfjlmuEfkDfanZ2dnUVZ_ramnZ2d@rcn.net> <URL:http://www.scipy.org/Cookbook/InputOutput> hth, Alan Isaac From steve at holdenweb.com Fri Feb 29 09:12:39 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 29 Feb 2008 09:12:39 -0500 Subject: call by reference howto???? In-Reply-To: <c52b8775-1656-471a-925c-867b3b649066@h11g2000prf.googlegroups.com> References: <47c5f9b8$0$21935$9b4e6d93@newsspool2.arcor-online.net> <492dbd31-6f65-4f36-b7af-acf42cf39d7d@34g2000hsz.googlegroups.com> <mailman.1428.1204286221.9267.python-list@python.org> <c52b8775-1656-471a-925c-867b3b649066@h11g2000prf.googlegroups.com> Message-ID: <fq93sr$unm$1@ger.gmane.org> castironpi at gmail.com wrote: > On Feb 29, 5:56 am, Steve Holden <st... at holdenweb.com> wrote: >> castiro... at gmail.com wrote: >>> On Feb 27, 6:02 pm, Tamer Higazi <n... at mail.de> wrote: >>>> Hi! >>>> Can somebody of you make me a sample how to define a function based on >>>> "call by reference" ??? >>>> I am a python newbie and I am not getting smart how to define functions, >>>> that should modify the variable I passed by reference. >>>> thanks in advance >>>> Tamer >>> If it's a mutable object, avoid the pitfalls of rebinding the >>> parameter, and just modify the object. >>> BAD: >>> def f( a ): >>> a= { 'this': 'that' } >>> GOOD: >>> def f( a ): >>> a.clear() >>> a[ 'this' ]= 'that' >> BETTER: >> >> class Thang: pass >> >> def f(a): >> a.this = "that" >> >> thang = Thang() >> f(thang) >> [please refrain from quoting signatures in your replies] [better still, use a mailer that omits them from the quote!] >> - Show quoted text - > > What does __coerce__ look like, so you could operate on a.this without > accessing 'this' member every time? For numbers maybe, but what about > __getattr__( self, name ): return getattr( self.this, name ) for > strings? Then thang.this= "that"; thang.find( 'at' ) -> > thang.this.find( 'at' ). Awesome! Where did __coerce__ come from? Stick with the main party, please. __coerce__ is an old mechanism intended to be used to bring numeric types into alignment, and AFAICS has nothing at all to do with whatever idea you are suggesting. As near as I can make out you appear to want to have thang delegate certain of its method to thang.this. The easiest way to do that would be to implement a __getattr__() in the Thang class to do so, but remember that it won't be called for cases where the class has a real attribute with the correct name. Hope this helps. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From grflanagan at gmail.com Fri Feb 29 15:32:24 2008 From: grflanagan at gmail.com (Gerard Flanagan) Date: Fri, 29 Feb 2008 12:32:24 -0800 (PST) Subject: joining strings question References: <6b41eaf1-05e1-4b04-8c31-6737166f267f@b1g2000hsg.googlegroups.com> <281b102e-0533-4357-8bab-9d3247fba719@e25g2000prg.googlegroups.com> <fzYxj.15333$Ch6.10415@newssvr11.news.prodigy.net> Message-ID: <2a984aee-5189-4252-96b5-005637fa2bc5@p73g2000hsd.googlegroups.com> On Feb 29, 7:56 pm, I V <ivle... at gmail.com> wrote: > On Fri, 29 Feb 2008 08:18:54 -0800, baku wrote: > > return s == s.upper() > > A couple of people in this thread have used this to test for an upper > case string. Is there a reason to prefer it to s.isupper() ? Premature decreptiude, officer... Gerard From castironpi at gmail.com Tue Feb 26 13:20:01 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 26 Feb 2008 10:20:01 -0800 (PST) Subject: is there enough information? References: <d9a0e758-1ce9-4b72-95b5-a1d8e99c5b46@p73g2000hsd.googlegroups.com> <56783fab-c5c5-4e42-a0fb-519f75beb65a@72g2000hsu.googlegroups.com> <0f240e82-04de-497f-a9aa-07458fc97235@b1g2000hsg.googlegroups.com> <03d54be8-b1a8-455b-9e1f-c75626aedc3e@72g2000hsu.googlegroups.com> <dedbaa9d-826b-44b2-a45e-52eca067f754@64g2000hsw.googlegroups.com> <8e2ce70d-0c7d-4d25-a646-3c48f2cfc839@q78g2000hsh.googlegroups.com> <6aWdnZhVGbG501nanZ2dnUVZ_q-jnZ2d@comcast.com> <b54bebf1-0635-4db7-9a74-a96b2382a232@u72g2000hsf.googlegroups.com> <Hdmdnb6Hu4gfyVnanZ2dnUVZ_uuqnZ2d@comcast.com> Message-ID: <b1a7846b-70ef-43ee-b141-b96d489ee5a6@72g2000hsu.googlegroups.com> On Feb 26, 12:04?pm, Jeff Schwab <j... at schwabcenter.com> wrote: > castiro... at gmail.com wrote: > > On Feb 26, 11:37 am, Jeff Schwab <j... at schwabcenter.com> wrote: > >> castiro... at gmail.com wrote: > >>> On Feb 26, 10:59 am, Preston ?Landers <pland... at gmail.com> wrote: > >>>> On Feb 26, 1:45 am, castiro... at gmail.com wrote: > >>>>> Two options occurred to me, which the first showed up in the earlier > >>>>> extremely skeletal and cryptic post: > >>>> Perhaps you would be more likely to get the kind of help you seem to > >>>> want > >>>> if you refrained from posting "cryptic and skeletal" messages. The > >>>> fact that many > >>>> other people have pointed this out to you as of late would tend to > >>>> suggest > >>>> you are trolling, i.e. intentionally trying to foster miscommunication > >>>> and threads > >>>> that do nothing to advance anyones understanding. > >>>> And regarding your other recent post about trying to find a "solution" > >>>> to the "problem" > >>>> of immutable types... ?Due to the above reasons you are unlikely to > >>>> influence the > >>>> design of the core language with half-baked stream of consciousness > >>>> ramblings. These > >>>> belong in your LiveJournal, not in c.l.python. > >>>> If you have a problem you need help with, please read this entire > >>>> document about 3 times > >>>> before posting anything else: > >>>>http://catb.org/~esr/faqs/smart-questions.html > >>>> Specifically this: > >>>>http://catb.org/~esr/faqs/smart-questions.html#beprecise > >>>> and this: > >>>>http://catb.org/~esr/faqs/smart-questions.html#goal > >>> Ugh, very well. ?You call for an explanation. > >>> Back home, the original post would be interesting, so I wrote it. > >>> Whatever reactions other people have to them is information that is > >>> unavailable to me. ?I don't know you. ?I'm rather irked by a > >>> proportion of posts, but for my part, it's hard to get me to point a > >>> finger. > >>> I am not a troll. ?I want a sustainable, healthy, productive, > >>> educational, informative relationship with frequenters of c.l.p, the > >>> Python community at large, and anyone who has anything non-negative to > >>> contribute. ?If you are wanting to see how I react to hostility, just > >>> ask. ?I'll fake it for you, but only for a second at a time. > >> Wow. ?I sure hope I don't come across like castiron does here. > > >>> Now, what help is it that you believe I seem to want? ?All I asked for > >>> was, ideas. > >> It's a little difficult for me to interpret your code, partly because I > >> am nbt very familiar with Python's support for concurrency. ?But what > >> are you trying to a achieve? > > >> You mentioned: ?"I recently ran into a case (* would that be helpful to > >> describe here?) where thread1 had to do something, thread2 had to do > >> something after that, and thread1 had to wait for that, then do > >> something else, and thread2 again had to wait before starting the first > >> thing again." > > >> This is ordinarily called a Producer-Consumer model. ?It is often > >> implemented using semaphores. ?Googling "python semaphore" turns up this > >> documentation: > > >>http://www.python.org/doc/lib/semaphore-objects.html > > >> That page, in turn, links to an example of the proper use of semaphores > >> in Python. ?Does that help?- Hide quoted text - > > >> - Show quoted text - > > > Hi Jeff. ?I've enjoyed your recent posts. > > > I'm not quite sure a semaphore is exactly the synchronization object > > I'm looking for, but I'm a little new to concurrency myself. > > > In the interface I design, only one with-call can get the result at > > once. ?It was my understanding that semaphores, and many other synch. > > objs. returned control at random. > > I take this to mean that your interface offers a function returns > immediately, rather than waiting for the work to complete. ?Is that correct? > > > In fact, in the background, I'm working on something a little more > > substantial than this, but it's not done, so the only review of it I > > can perform is of its interface. > > The interface is (in my opinion) usually the best place to start the > code, anyway. > > > If someone has a "yes, but in half the lines, at twice the speed," > > then tear my posts to shreds. > > It is not quite clear what your code is intended to do. ?That doesn't > mean there's necessarily anything wrong with it, but it's hard for most > Usenetters to take the time to read such long sequences of code. ?Would > it be possible for you to post a complete program, that we can actually > run? ?Wherever your code is not yet ready, just put a line or two of > "stub" code, and add a comment to explain what should be happening.- Hide quoted text - > > - Show quoted text - Sure. And honestly, I have no idea what the best way to go about this is, except keep trying. th1 th2 set cmd run cmd get result acknowledge continue continue th2 won't -run cmd- until th1 completes -set cmd-. th1 won't -get result- until th2 completes -run cmd-. and once -acknowledge- completes, both can go about their merry ways. In the example last night, th2 continued to loop to handle requests in a collection of threads, but th1 had pressing business elsewhere. Dated 05:07 PST, the code should be runnable. But the only thing is, I developed it in Python 3.0a2. In particular, line 71 def thloop( thd ), and line 82 def op100( thd ), should demonstrate that interface. Newsgroups: comp.lang.python From: castiro... at gmail.com Date: Tue, 26 Feb 2008 05:07:48 -0800 (PST) Local: Tues, Feb 26 2008 7:07 am Subject: Re: is there enough information? The interface is an awesome place to start. From steve at holdenweb.com Fri Feb 1 05:52:13 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 01 Feb 2008 05:52:13 -0500 Subject: psycopg2 In-Reply-To: <Pine.LNX.4.64.0802011059510.4778@eingang.hrz.tu-chemnitz.de> References: <Pine.LNX.4.64.0802010115420.3456@eingang.hrz.tu-chemnitz.de> <mailman.125.1201826324.9267.python-list@python.org> <Pine.LNX.4.64.0802011059510.4778@eingang.hrz.tu-chemnitz.de> Message-ID: <47A2F9DD.1080202@holdenweb.com> Andre' John wrote: > Thanks very much, this was indeed the problem. That column was an array. > I created it via GUI and was wondering why it did append a '[]' to the > variable type, but didn't bother, because there was no other varchar > available. > If you're using pgAdmin then try "character varying" - then your original SQL should work correctly! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From duncan.booth at invalid.invalid Thu Feb 21 11:40:42 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 21 Feb 2008 16:40:42 GMT Subject: Globals or objects? (is: module as singleton) References: <mailman.1066.1203611228.9267.python-list@python.org> Message-ID: <Xns9A4BA99F8A23Cduncanbooth@127.0.0.1> "James Newton" <jnewton at fuelindustries.com> wrote: > Perhaps my real question is about how to visualize a module: what makes > an imported module different from an instance? On one level: nothing. An imported module is an instance of the module type. Modules don't have to be associated with python code: you can create additional module instances (by calling new.module) and populate them however you wish. What you get with a module is support for locating a specific module and ensuring that you don't get duplicate copies of a named module. What you lose is the ability to define methods: functions in a module don't have a 'self' parameter. Also you can't override special methods for a module, so it isn't quite equivalent to writing a class, but there are similarities. Regarding your question about saving the values: what you would usually do would be to store the values in a separate configuration file and the module would load them on startup and then rewrite the configuration file when you call a save function. That way the module code itself isn't changing. The 'singleton' config module would expose functions such as 'load', 'save', 'getXXX'. From python-url at phaseit.net Mon Feb 4 11:24:37 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Mon, 4 Feb 2008 16:24:37 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Feb 4) Message-ID: <fo7e85$ml6$1@lairds.us> QOTW: "Everyone with a PC knows that eventually their computer will slow down, crash unexpectedly, and develop problems with applications." - promotional materials for award-winning *Degunking Windows* book "It's a very good idea to read the entire FAQ as soon as you've gotten past the very basic Python level, so that you can save yourself and others a lot of time stumbling over the traditional problems that everyone goes through. You'll learn a lot of useful things in the process." - Peter Hansen Module/package hierarchy and its separation from file structure: http://groups.google.com/group/comp.lang.python/browse_thread/thread/5a9580e76484f73/ Notes on running multiple interpreters in the same process: http://groups.google.com/group/comp.lang.python/browse_thread/thread/f044df524c426027/ Type annotations, type inference and static typing for Python: http://groups.google.com/group/comp.lang.python/browse_thread/thread/e7d39693de66e6f1/ Is Python "standardised" or not? (Wikipedia entry): http://groups.google.com/group/comp.lang.python/browse_thread/thread/a828c6585be8a682/ Should be a better way of saying `do_something n times` than this: `for i in range(n): do_something` http://groups.google.com/group/comp.lang.python/browse_thread/thread/cd391ce323f3d8f6/ Dictionary comprehensions: discarded in the past, now on Python 3.0: http://groups.google.com/group/comp.lang.python/browse_thread/thread/8f3650ba5da77543/ ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html Steve Bethard continues the marvelous tradition early borne by Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim Lesher of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topic/python/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to <Python-URL at phaseit.net> should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask <claird at phaseit.net> to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From mensanator at aol.com Thu Feb 7 19:01:12 2008 From: mensanator at aol.com (mensanator at aol.com) Date: Thu, 7 Feb 2008 16:01:12 -0800 (PST) Subject: brain stuck. whats occurring here? References: <mailman.468.1202405913.9267.python-list@python.org> <c13dc924-8ce2-411b-88ab-c20d27332dd6@f10g2000hsf.googlegroups.com> <mailman.480.1202418837.9267.python-list@python.org> Message-ID: <2bbb805e-1dcb-44fa-a950-7fbf6500dc61@i12g2000prf.googlegroups.com> On Feb 7, 3:13?pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote: > En Thu, 07 Feb 2008 16:16:11 -0200, mensana... at aol.com ? > <mensana... at aol.com> escribi?: > > > On Feb 7, 11:38?am, Matthew_WAR... at bnpparibas.com wrote: > > I don't see why you should get either. > > > Especially considering this behaviour: > > >>>> a=[] > >>>> row=[ [] for n in range(0,10) ] > >>>> a.extend(row[:]) > >>>> a > > [[], [], [], [], [], [], [], [], [], []] > >>>> a[0].extend(row[:]) > >>>> a > > [[[...], [], [], [], [], [], [], [], [], []], [], [], [], [], [], [], > > [], [], []] > > Those [...] should give a clue. Usually Python doesn't "shorten" a list ? > representation: if it takes a thousand lines to output a list, there will ? > be a thousand lines of output. The [...] means that the list is ? > *recursive*: it has an element that refers to the list itself, so it can't ? > be represented in the normal way. > Why is it recursive? row[:] is a new list, not the same object as row. It ? > is a copy - but a "shallow" copy, because their elements aren't copies ? > themselves. So row[0] is the same object as row[:][0] > > >>> x = row[:] > >>> x == row > True > >>> x is row > False > >>> x[0] is row[0] > > True > > In the line a[0].extend(row[:]), a[0] is THE SAME LIST as row[:][0], the ? > first item you are appending. That is, the first thing extend() does is ? > conceptually a[0].append(a[0]) - and you got a recursive structure. I thought that it was some kind of recursive hocus pocus. That explains why no matter how many indexes I ask for, I always get the same result. >>> a[0][0][0][0][0][0][0][0][0][0][0][0][0][0] [[...], [], [], [], [], [], [], [], [], []] > > > Bug in IDLE? > > No, just a misunderstanding of what [:] does, I presume. You didn't answer my question, but I just realize that I mis-typed my example, so never mind. > > -- > Gabriel Genellina From grante at visi.com Mon Feb 25 11:27:15 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 25 Feb 2008 16:27:15 -0000 Subject: How about adding rational fraction to Python? References: <b2b884df-b499-4740-9d21-cae87bbd790d@q77g2000hsh.googlegroups.com> <198927a7-9478-42b3-a972-82049f0130ac@u10g2000prn.googlegroups.com> <1bc9bba7-dc7f-4cfe-8e1c-fa5901c9f556@n77g2000hse.googlegroups.com> <97f30679-483d-4751-9a6e-0858b36eb426@d4g2000prg.googlegroups.com> <mailman.1169.1203875215.9267.python-list@python.org> <f4443376-04a0-414e-9eba-149bf9779bef@34g2000hsz.googlegroups.com> <649ac8a9-ae09-4e9b-85c2-f37043af21fd@28g2000hsw.googlegroups.com> <edd61692-2b00-405c-adfe-7f5224097e95@e10g2000prf.googlegroups.com> <ead37b53-5174-4a54-ae36-f0e1be1dd065@z17g2000hsg.googlegroups.com> <fpt11h$uob$1@aioe.org> <0d1955fc-762c-44e1-a5d8-372c71458455@p25g2000hsf.googlegroups.com> <36204e6f-0d82-449b-8ca5-c819ace9a55a@p73g2000hsd.googlegroups.com> <f32fa9e5-feb2-4d30-845a-447dbce6b19a@p73g2000hsd.googlegroups.com> <9503b14b-7bd5-42b4-b3f7-673d0ebd7feb@c33g2000hsd.googlegroups.com> Message-ID: <13s5r338rrtuq3f@corp.supernews.com> On 2008-02-25, Carl Banks <pavlovevidence at gmail.com> wrote: > In other words, 3/4 in Python rightly yields a float Unless you're in the camp that believes 3/4 should yield the integer 0. ;) > and not a rational. -- Grant Edwards grante Yow! Zippy's brain cells at are straining to bridge visi.com synapses ... From http Sat Feb 23 23:25:31 2008 From: http (Paul Rubin) Date: 23 Feb 2008 20:25:31 -0800 Subject: Article of interest: Python pros/cons for the enterprise References: <e5ae7c80-8bb7-4903-92ff-89e4f62c0239@b29g2000hsa.googlegroups.com> <2f1527a7-2f66-44c7-9665-4d8ff01fa5ab@28g2000hsw.googlegroups.com> <47bd4a24$0$25225$426a74cc@news.free.fr> <f9547b0a-bffa-44b3-8638-12b1dd88fe49@p43g2000hsc.googlegroups.com> <mailman.1057.1203605188.9267.python-list@python.org> <ae0cf9a7-842d-4edf-bd1a-bf4057a694c5@q70g2000hsb.googlegroups.com> <784ec210-f389-4a15-b458-961100de9103@v3g2000hsc.googlegroups.com> <ca9a03a4-ab5e-4e0f-92e4-4982386d7a8e@d5g2000hsc.googlegroups.com> <5MSdncqVGdEXiSPanZ2dnUVZ_vPinZ2d@comcast.com> <d2777845-6684-4a18-9c8a-e4f58e4e6781@q70g2000hsb.googlegroups.com> <AcWdnV4sAZmqwSPanZ2dnUVZ_oSunZ2d@comcast.com> <7xwsoxd00c.fsf@ruckus.brouhaha.com> <f76dnYohFaXb0V3anZ2dnUVZ_u-unZ2d@comcast.com> <mailman.1145.1203814683.9267.python-list@python.org> <JIudnfqUz6mjR13anZ2dnUVZ_rWtnZ2d@comcast.com> <7xr6f3f3ma.fsf@ruckus.brouhaha.com> <DfednXiRDZffdV3anZ2dnUVZ_vamnZ2d@comcast.com> Message-ID: <7xhcfzdlqc.fsf@ruckus.brouhaha.com> Jeff Schwab <jeff at schwabcenter.com> writes: > > there's actually a published book specifically about C++ pitfalls. > > Mercy, a whole book? http://search.barnesandnoble.com/booksearch/isbnInquiry.asp?EAN=9780201179286 > > C and C++ should practically be outlawed at this point. > > On what grounds? "I don't approve of the programming language you're > using. Cease and desist. Nyah!" Well, "outlawed" of course is a figure of speech; however use of those languages should be a red flag in a design review, and a factor in determining product liability if a program misbehaves. Think of all the buffer overflow exploits against Microsoft Windows programs that couldn't have happened if Microsoft had used safer languages. There was clearly a failure to use best engineering practices. From gherron at islandtraining.com Sun Feb 3 13:06:50 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 03 Feb 2008 10:06:50 -0800 Subject: Python GUI toolkit In-Reply-To: <WOednR5mwcsIRzjanZ2dnUVZ_oaonZ2d@giganews.com> References: <WOednR5mwcsIRzjanZ2dnUVZ_oaonZ2d@giganews.com> Message-ID: <47A602BA.3000407@islandtraining.com> default at defaulted.default wrote: > what would be the best python GUI toolkit, it must be cross platform. > > i have tried gtk, but it interface are real bad and its coding was difficult > so i dropped it, > > the only remaining are qt4 and wx, i would like to know if one of these or > any other toolkit is capable of creating good-looking GUI's, like in other > apps, for e.g, .net apps. > Not true! There are *many* more widget toolkits out there. Dozens! See: http://en.wikipedia.org/wiki/List_of_widget_toolkits Gary Herron > i m a noob, and willing to learn, so difficulty is no problem > From grante at visi.com Tue Feb 26 12:28:29 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 26 Feb 2008 17:28:29 -0000 Subject: How about adding rational fraction to Python? References: <b2b884df-b499-4740-9d21-cae87bbd790d@q77g2000hsh.googlegroups.com> <1bc9bba7-dc7f-4cfe-8e1c-fa5901c9f556@n77g2000hse.googlegroups.com> <97f30679-483d-4751-9a6e-0858b36eb426@d4g2000prg.googlegroups.com> <mailman.1169.1203875215.9267.python-list@python.org> <f4443376-04a0-414e-9eba-149bf9779bef@34g2000hsz.googlegroups.com> <649ac8a9-ae09-4e9b-85c2-f37043af21fd@28g2000hsw.googlegroups.com> <edd61692-2b00-405c-adfe-7f5224097e95@e10g2000prf.googlegroups.com> <ead37b53-5174-4a54-ae36-f0e1be1dd065@z17g2000hsg.googlegroups.com> <fpt11h$uob$1@aioe.org> <0d1955fc-762c-44e1-a5d8-372c71458455@p25g2000hsf.googlegroups.com> <36204e6f-0d82-449b-8ca5-c819ace9a55a@p73g2000hsd.googlegroups.com> <f32fa9e5-feb2-4d30-845a-447dbce6b19a@p73g2000hsd.googlegroups.com> <9503b14b-7bd5-42b4-b3f7-673d0ebd7feb@c33g2000hsd.googlegroups.com> <602ac27c-4aaa-49b2-bee2-1e0e0c705983@i7g2000prf.googlegroups.com> Message-ID: <13s8j1tglqpth80@corp.supernews.com> On 2008-02-26, Lie <Lie.1296 at gmail.com> wrote: >> I'm in the camp that believes that 3/4 does indeed yield the integer 0, >> but should be spelled 3//4 when that is the intention. > > That's creepy for people that are new to programming and doesn't know > how CPUs work and are used to general mathematics. I don't know where you went to grade school, but where I went, we learned about integer division long before we learned about floating point. > That means most people. I guess it must depend on where you went to shool. > As programming language are now more accessible to regular > people without specialized Computer Science degree, it is a > just natural trend that computer arithmetic must be done in an > expectable manner as seen by those general population not by > people who holds a CS degree. -- Grant Edwards grante Yow! You were s'posed at to laugh! visi.com From ricaraoz at gmail.com Sun Feb 24 21:35:17 2008 From: ricaraoz at gmail.com (=?UTF-8?B?UmljYXJkbyBBcsOhb3o=?=) Date: Sun, 24 Feb 2008 23:35:17 -0300 Subject: Is there a open souce IDE writen by C( C++) or partly writen by C( C++)? In-Reply-To: <0bee58a3-bdc9-47fe-b9a4-7750cc3ebcb5@s12g2000prg.googlegroups.com> References: <42a838b9-2023-4cbf-bc53-e7ac5f4accbc@i7g2000prf.googlegroups.com> <47BE6D27.7000305@behnel.de> <ef7059c4-d619-41c1-b807-c485345676d7@s37g2000prg.googlegroups.com> <c1528422-5db2-4193-919b-b0a851d973f4@b29g2000hsa.googlegroups.com> <47bee4d6$0$15901$edfadb0f@dtext01.news.tele.dk> <c4033e0a-96c0-40cd-bcb1-3287e12de20b@c33g2000hsd.googlegroups.com> <f477bd34-a90b-4f55-985a-3d67950c1175@i7g2000prf.googlegroups.com> <mailman.1140.1203803295.9267.python-list@python.org> <fc9b4dc0-10c7-49b5-9d50-5ab0ee9841e3@e25g2000prg.googlegroups.com> <mailman.1182.1203888933.9267.python-list@python.org> <0bee58a3-bdc9-47fe-b9a4-7750cc3ebcb5@s12g2000prg.googlegroups.com> Message-ID: <47C22965.7080507@bigfoot.com> zaley wrote: >>> So I hope I can find something helpful in open source IDE for python. >> Exactly so. PyScripter does it easy, besides you can have in different >> tabs all the modules of your application. You just hit the run button >> and your program runs, you hit the debug button and you start going step >> by step. It's free, easy to install, just give it a try and if you don't >> like it just trash it. > > I just want to know how to do it!! Ok, I hope I'm not misunderstanding you. You go to http://www.mmm-experts.com/Downloads.aspx and you download PyScripter (windows installer). Then you run the downloaded file (that would be PyScripter-setup.exe) and that will install PyScripter in your machine. You run PyScripter, click the "open" button or menu File/Open... and choose the program you want to debug. It will be opened in an edit window in your PyScripter main window. Then you click on "Step into subroutine" button or just press <F7> and you'll be in the first line of your program. From then on you keep clicking "Step into subroutine" (<F7>) or "Step over next function call" (<F8>) or "Step out of the current subroutine" or "Run to cursor" as you see fit. You can add breakpoints just by clicking to the left of the line numbers or the appropriate button. You can watch what's going on in your program in the lower partition of your main window where you have a "Call Stack" tab and also "Variables", "Watches", "Breakpoints", "Output" and "Messages" tabs. >From then on you are on your own. HTH From agenkin at gmail.com Thu Feb 7 10:25:14 2008 From: agenkin at gmail.com (agenkin at gmail.com) Date: Thu, 7 Feb 2008 07:25:14 -0800 (PST) Subject: Looking for library to estimate likeness of two strings References: <86e63d06-124e-49e8-82e2-dfbea01fcce7@v17g2000hsa.googlegroups.com> Message-ID: <5bf3752a-96c5-4bc7-aa4b-05ff0a544a82@s8g2000prg.googlegroups.com> Hi, All: Many thanks for the excellent leads. I've also found several functions to find phonetic similarity between English names: the mentioned above soundex, then, also, one called metaphone. I'm now thinking of the best way to use some combination of these functions. From tomdiz at yahoo.com Sun Feb 3 02:56:13 2008 From: tomdiz at yahoo.com (Thomas DiZoglio) Date: Sat, 2 Feb 2008 23:56:13 -0800 (PST) Subject: Windows Python 2.5.1 IPV6 problems In-Reply-To: <47a571ce$0$14409$9b622d9e@news.freenet.de> Message-ID: <203165.6099.qm@web53512.mail.re2.yahoo.com> Hi, Thanks for the help. I had to make family and int. It was defined as socket.AF_INET6 and for some reason not making that an int. It is fix now. ------------------- t0md --- "Martin v. L?wis" <martin at v.loewis.de> wrote: > > _sock = _realsocket(family, type, proto) > > TypeError: an integer is required > > So what values have family, type, and proto at that > point? > Edit socket.py to find out. > > Could it be that you also need to set socketType for > your > Port subclass? > > Regards, > Martin > -- > http://mail.python.org/mailman/listinfo/python-list > CONFIDENTIALITY NOTICE: Proprietary/Confidential Information belonging to Virgil Software, Inc. may be contained in this message. If you are not a recipient indicated or intended in this message (or responsible for delivery of this message to such person), or you think for any reason that this message may have been addressed to you in error, you may not use or copy or deliver this message (and all attachments) to anyone else. In such case, you should destroy this message (and all attached documents) and are asked to notify the sender by reply email. ____________________________________________________________________________________ Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ From python.list at tim.thechases.com Thu Feb 7 16:57:17 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 07 Feb 2008 15:57:17 -0600 Subject: beginners help In-Reply-To: <13qmu44hh60ced9@corp.supernews.com> References: <47aaffb2$0$85781$e4fe514c@news.xs4all.nl> <13qmu44hh60ced9@corp.supernews.com> Message-ID: <47AB7EBD.4000809@tim.thechases.com> > If i enter a center digit like 5 for example i need to create two > vertical and horzitonal rows that looks like this. If i enter 6 it shows > 6 six starts. How can i do this, because i don't have any clue. > > ***** > * * > * * > * * > ***** Well we start by introducing the neophite programmer to unit-testing: import unittest class Tester(unittest.TestCase): def testFive(self): """ digit like 5 for example i need to create two vertical and horzitonal rows that looks like this ***** * * * * * * ***** """ assert five() == "*****\n* *\n* *\n* *\n*****" def testSix(self): """If i enter 6 it shows 6 six starts""" assert six() == "start" * 6 def five(): return "*****\n* *\n* *\n* *\n*****" def six(): return "start" * 6 if __name__ == "__main__": unittest.main() works for me... ;) -tkc From bharathv6 at gmail.com Wed Feb 20 12:20:16 2008 From: bharathv6 at gmail.com (bharath venkatesh) Date: Wed, 20 Feb 2008 09:20:16 -0800 Subject: threaded http server In-Reply-To: <47BC5CCD.8080905@cheimes.de> References: <910313af0802200417if1e6422p47ca1a22cb23c8ac@mail.gmail.com> <fphb94$f2m$1@ger.gmane.org> <910313af0802200845p46970afas5a368dc9c3c80a05@mail.gmail.com> <47BC5CCD.8080905@cheimes.de> Message-ID: <910313af0802200920p1d2bc144p2f96ada962802cb1@mail.gmail.com> oh .. thanks for explaining .... since this is my first ever project i don't know much ... can u give me a basic idea of how it(image_proxy_server) can be done efficiently .. like serving many clients concurrently On Feb 20, 2008 9:01 AM, Christian Heimes <lists at cheimes.de> wrote: > bharath venkatesh wrote: > > hi, > > will this twisted,turbo gear etc help me to create a http server that > can > > serve multiple clients concurrently.... > > and also the http server which i want to create in my project will not > be > > doing any IO (it is not like frontend and backend ).. but it will act > as a > > image_proxy_server i.e when a client wants an image it will do a http > > request to my http server if the image is present in cache it will > fetch it > > directly from cache and return it to the client as an http reponse > > otherwise it fetch from www and store it cache and also return it > to > > the client as an http response so basically i want to serve many clients > > concurrently in fast n efficient manner > > You are reading data from a network socket (IO), you are serving images > from a disk cache or memory cache (IO) or you are retrieving images from > a remote site (IO). > > Your application is most certainly not using the CPU much. All you do is > serving data or reading data - input and output - IO. :) > > Christian > > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080220/8a48abfa/attachment.html> From http Fri Feb 22 16:38:04 2008 From: http (Paul Rubin) Date: 22 Feb 2008 13:38:04 -0800 Subject: Simple - looking for a way to do an element exists check.. References: <d45626f2-99f6-42cc-b6fe-d109c114cf2f@n77g2000hse.googlegroups.com> <7x8x1c25cz.fsf@ruckus.brouhaha.com> <7x3ark2560.fsf@ruckus.brouhaha.com> <ef20db75-a697-4097-aaec-af7d4b73cdde@p43g2000hsc.googlegroups.com> Message-ID: <7xwsowd64j.fsf@ruckus.brouhaha.com> Paul McGuire <ptmcg at austin.rr.com> writes: > I think you have this backwards. Should be: > > if not any(x[0]==element[0] for x in a): > a.append(element) I think you are right, it was too early for me to be reading code when I posted that ;-) From Matthew_WARREN at bnpparibas.com Fri Feb 1 05:40:11 2008 From: Matthew_WARREN at bnpparibas.com (Matthew_WARREN at bnpparibas.com) Date: Fri, 1 Feb 2008 10:40:11 +0000 Subject: very simple Genetic Algorithm completed In-Reply-To: <c11f0b75-094a-4d22-988d-e7477846ebfa@d70g2000hsb.googlegroups.com> Message-ID: <OF32DBBF0D.730C2C7A-ON802573E2.0039D053-802573E2.003A9C4E@bnpparibas.com> Usually. I this case though, I really wasnt planning ahead too much as I wrote it and thats the way it happened... not the best of excuses I know. I've been thinking about the consequences though, and I'd have to run it to see really, but I'm thinking looking for average population fitness should produce more individuals within the population that are fit, whereas stopping as soon as one individual is fit enough in the population wouldn't give the others a chance to catch up as it were ! .. theres all kinds of ways of approaching it, and I just picked a quick simple one on the fly. I've already noticed stray bits of code in there, so as I clean it up I'll put in the individual fitnes test in and see how it goes. As an aside; anyone here played with Framsticks? Matt. I must not anthropomorphise sequences of symbols. (apologies disclaimers) This message and any attachments (the "message") is intended solely for the addressees and is confidential. If you receive this message in error, please delete it and immediately notify the sender. Any use not in accord with its purpose, any dissemination or disclosure, either whole or partial, is prohibited except formal approval. The internet can not guarantee the integrity of this message. BNP PARIBAS (and its subsidiaries) shall (will) not therefore be liable for the message if modified. Do not print this message unless it is necessary, consider the environment. --------------------------------------------- Ce message et toutes les pieces jointes (ci-apres le "message") sont etablis a l'intention exclusive de ses destinataires et sont confidentiels. Si vous recevez ce message par erreur, merci de le detruire et d'en avertir immediatement l'expediteur. Toute utilisation de ce message non conforme a sa destination, toute diffusion ou toute publication, totale ou partielle, est interdite, sauf autorisation expresse. L'internet ne permettant pas d'assurer l'integrite de ce message, BNP PARIBAS (et ses filiales) decline(nt) toute responsabilite au titre de ce message, dans l'hypothese ou il aurait ete modifie. N'imprimez ce message que si necessaire, pensez a l'environnement. From arnodel at googlemail.com Wed Feb 27 12:27:02 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 27 Feb 2008 09:27:02 -0800 (PST) Subject: Making string-formatting smarter by handling generators? References: <mailman.1355.1204129432.9267.python-list@python.org> Message-ID: <53b40b65-a8d5-4bc9-b740-10fb5f9170b6@41g2000hsc.googlegroups.com> On Feb 27, 4:23?pm, Tim Chase <python.l... at tim.thechases.com> wrote: > Is there an easy way to make string-formatting smart enough to > gracefully handle iterators/generators? ?E.g. > > ? ?transform = lambda s: s.upper() > ? ?pair = ('hello', 'world') > ? ?print "%s, %s" % pair # works > ? ?print "%s, %s" % map(transform, pair) # fails > > with a """ > TypeError: ?not enough arguments for format string > """ > > I can force it by wrapping the results of my generator in a call > to tuple() or list() (Are you using python 3.0 ? For python < 3, map returns a list) list() wouldn't work as % expects a tuple (otherwise it considers that only one argument is needed). The problem would arise with any non- tuple iterable, not just generators. See http://docs.python.org/lib/typesseq-strings.html > > ? ?print "%s, %s" % tuple(map(transform, pair)) > > but it feels a bit hackish to me. I think it is the way to do it though. > I find I hit it mostly with calls to map() where I want to apply > some transform (as above) to all the items in a list of > parameters such as > > ? ?"%s=%s&%s=%s" % map(urllib.quote, params) > > Any suggestions? ?(even if it's just "get over your hangup with > wrapping the results in list()/tuple()" :) get over your hangup with wrapping the results in tuple()! (not list() though, as explained above). Or you could always define def tmap(*args): return tuple(map(*args)) -- Arnaud From steve at holdenweb.com Thu Feb 7 09:07:41 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 07 Feb 2008 09:07:41 -0500 Subject: python beginner problem(?) In-Reply-To: <13qm2biij74c254@news.supernews.com> References: <13qkgb8iub6bv2d@news.supernews.com><47AA4AC1.6080404@holdenweb.com> <mailman.424.1202352008.9267.python-list@python.org> <13qm2biij74c254@news.supernews.com> Message-ID: <fof3be$lcf$2@ger.gmane.org> Alan Illeman wrote: > "Steve Holden" <steve at holdenweb.com> wrote in message > news:mailman.424.1202352008.9267.python-list at python.org... >> Steve Holden wrote: >>> Alan Illeman wrote: >>>> Win2k Pro - installed python: ok >>>> >> [...] >>>> ================================================= >>>>>>> C:\Python25\Lib\site-packages\pythonwin\pywin\mfc\object.py: >>>> 23: DeprecationWarning: raising a string exception is deprecated >>>> raise win32ui.error, "The MFC object has died." >>>> pwd=secret;database=master;uid=sa;server=mpilgrim >>>> ================================================= >>>> >>>> DiveIntoPython example 2.1 result: >>>> server=mpilgrim;uid=sa;database=master;pwd=secret >>>> >>>> ..which I realise is essentially the same (except for order). >>>> >>>> I haven't ever (not that I remember) installed MFC. >>>> >>>> Help! >>>> >> [...] >>> I am hugely surprised to find that PythonWin apparently raises string >>> exceptions: this is an old programming technique, which should have been >>> removed from anything designed to run on Python 2.5. That is why you see >>> the message: it's only a warning, so you can ignore it. I am copying >>> Mark on this message in case he's unaware of the issue. >> [...] >> >> In a private reply Mark Hammond says he will fix this in the next >> release - thanks for the report! >> >> regards >> Steve >> -- >> Steve Holden +1 571 484 6266 +1 800 494 3119 >> Holden Web LLC http://www.holdenweb.com/ > > Thanks Steve for both your replies. > Was (or is) python a piggyback for MFC? > > You are supposed to be able to access the MFC classes through PythonWin, but I have never personally bothered because MFC is too horrible to tangle with. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From python.list at tim.thechases.com Mon Feb 11 14:36:24 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 11 Feb 2008 13:36:24 -0600 Subject: how to find current working user In-Reply-To: <D8D2AEA3575B364DAC5F27D00A5E0D1791AF04@PA-EXCH03.vmware.com> References: <D8D2AEA3575B364DAC5F27D00A5E0D1791AF04@PA-EXCH03.vmware.com> Message-ID: <47B0A3B8.9090802@tim.thechases.com> > Can anyone tell me how to find current working user in windows? The below should be fairly cross-platform: >>> import getpass >>> whoami = getpass.getuser() >>> print whoami W: tchase L: tim ("W:" is the result on my windows box, "L:" is the result on my Linux box) which can be used in concert with >>> import user >>> print user.home W: C:\Documents and Settings\tchase L: /home/tim or >>> import os >>> os.expanduser('~/Desktop') W: C:\Documents and Settings\tchase/Desktop L: /home/tim/Desktop in case you need either of them. -tkc From jeff at schwabcenter.com Tue Feb 26 12:07:34 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Tue, 26 Feb 2008 09:07:34 -0800 Subject: Article of interest: Python pros/cons for the enterprise In-Reply-To: <b9cd2ec4-5008-4c6e-9741-bdda460afa92@71g2000hse.googlegroups.com> References: <e5ae7c80-8bb7-4903-92ff-89e4f62c0239@b29g2000hsa.googlegroups.com> <mailman.1057.1203605188.9267.python-list@python.org> <ae0cf9a7-842d-4edf-bd1a-bf4057a694c5@q70g2000hsb.googlegroups.com> <784ec210-f389-4a15-b458-961100de9103@v3g2000hsc.googlegroups.com> <ca9a03a4-ab5e-4e0f-92e4-4982386d7a8e@d5g2000hsc.googlegroups.com> <5MSdncqVGdEXiSPanZ2dnUVZ_vPinZ2d@comcast.com> <d2777845-6684-4a18-9c8a-e4f58e4e6781@q70g2000hsb.googlegroups.com> <AcWdnV4sAZmqwSPanZ2dnUVZ_oSunZ2d@comcast.com> <7xwsoxd00c.fsf@ruckus.brouhaha.com> <f76dnYohFaXb0V3anZ2dnUVZ_u-unZ2d@comcast.com> <mailman.1145.1203814683.9267.python-list@python.org> <JIudnfqUz6mjR13anZ2dnUVZ_rWtnZ2d@comcast.com> <7xr6f3f3ma.fsf@ruckus.brouhaha.com> <DfednXiRDZffdV3anZ2dnUVZ_vamnZ2d@comcast.com> <7xhcfzdlqc.fsf@ruckus.brouhaha.com> <b9cd2ec4-5008-4c6e-9741-bdda460afa92@71g2000hse.googlegroups.com> Message-ID: <mp-dnaqeJPOz2lnanZ2dnUVZ_sSlnZ2d@comcast.com> Nicola Musatti wrote: > On Feb 24, 5:25 am, Paul Rubin <http://phr... at NOSPAM.invalid> wrote: >> Jeff Schwab <j... at schwabcenter.com> writes: >>>> there's actually a published book specifically about C++ pitfalls. >>> Mercy, a whole book? >> http://search.barnesandnoble.com/booksearch/isbnInquiry.asp?EAN=97802... > > Read the title. This is about "C Traps and Pitfalls". Although it > shows its age, it's still worth reading. Unfortunately from its price > you'd think it was handwritten. That is not a book about C++ pitfalls. That is a book about C pitfalls. They really are two very different languages. Don't get me wrong, C++ has pitfalls of its own -- perhaps the worst of which is writing C and thinking it's C++ in anything other than a superficial sense. But there are vanishingly few cases that could lead to out-of-bounds indexes or dangling pointers anymore. From grante at visi.com Fri Feb 8 10:30:18 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 08 Feb 2008 15:30:18 -0000 Subject: Why not a Python compiler? References: <87tzkko6dv.fsf@physik.rwth-aachen.de> <A20311AF91C11640ACBB721DC2558B4906C9F26C@brexc51p> <mailman.482.1202419858.9267.python-list@python.org> Message-ID: <13qotcag5lp3r81@corp.supernews.com> On 2008-02-07, Jeroen Ruigrok van der Werven <asmodai at in-nomine.org> wrote: > -On [20080207 22:09], Reedick, Andrew (jr9445 at ATT.COM) wrote: >>Errr... didn't one of the novels explain it away by describing the >>kessel run as a region of space warped by black holes or other objects? >>Bragging rights for crossing such a field thus centered on shortest >>distance instead of time. > > http://starwars.wikia.com/wiki/Kessel_Run > > Han Solo claimed that his Millennium Falcon "made the Kessel Run in less > than twelve parsecs." The parsec is a unit of distance, not time. Solo was > not referring directly to his ship's speed when he made this claim. Instead, > he was referring to the shorter route he was able to travel by skirting the > nearby Maw black hole cluster, thus making the run in under the standard > distance. However, parsec relates to time in that a shorter distance equals > a shorter time at the same speed. By moving closer to the black holes, Solo > managed to cut the distance down to about 11.5 parsecs. Um, yea, I'd have to call bullshit on that. IIRC, he was answering a question something like "is she fast". If you buy the above BS, he'd have to be be answering a question about his piloting skills not about how fast the ship is. One could give GL the benefit of the doubt and claim that GL intentionally miswrote the line to give the movie the feel of the badly-written serials he was emulating. But then again, I think GL has since proven beyond a doubt that he's just a really bad writer who is particularly awful at dialog. > In the A New Hope novelization, Han says "standard time units" > rather than "parsecs". Therefore, the reduced distance of > Solo's Kessel Run is most likely a retcon to explain George > Lucas's confusion of time and distance units. -- Grant Edwards grante Yow! BELA LUGOSI is my at co-pilot ... visi.com From python.list at tim.thechases.com Wed Feb 6 17:28:37 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 06 Feb 2008 16:28:37 -0600 Subject: Looking for library to estimate likeness of two strings In-Reply-To: <86e63d06-124e-49e8-82e2-dfbea01fcce7@v17g2000hsa.googlegroups.com> References: <86e63d06-124e-49e8-82e2-dfbea01fcce7@v17g2000hsa.googlegroups.com> Message-ID: <47AA3495.2090005@tim.thechases.com> > Are there any Python libraries implementing measurement of similarity > of two strings of Latin characters? It sounds like you're interested in calculating the Levenshtein distance: http://en.wikipedia.org/wiki/Levenshtein_distance which gives you a measure of how different they are. A measure of "0" is that the inputs are the same. The more different the two strings are, the greater the resulting output of the function. Unfortunately, it's an O(MN) algorithm (where M=len(word1) and N=len(word2)) from my understanding of the code I've seen. However it really is the best approximation I've seen of a "how similar are these two strings" function. Googling for python levenshtein distance brings up oodles of hits. -tkc From hv at tbz-pariv.de Tue Feb 19 11:23:19 2008 From: hv at tbz-pariv.de (Thomas Guettler) Date: Tue, 19 Feb 2008 17:23:19 +0100 Subject: psycopg2: connect copy_from and copy_to In-Reply-To: <fc6ec7dd-8b23-4156-ae44-908ff486204e@p43g2000hsc.googlegroups.com> References: <6209kgF20tdpgU1@mid.individual.net> <fc6ec7dd-8b23-4156-ae44-908ff486204e@p43g2000hsc.googlegroups.com> Message-ID: <620e3oF21itlbU1@mid.individual.net> > Doesn't PostGres come with Export/Import apps ? That would be easiest > (and faster). Yes, you can use "pg_dump production ... | psql testdb", but this can lead to dead locks, if you call this during a python script which is in the middle of a transaction. The python script locks a table, so that psql can't write to it. I don't think calling pg_dump and psql/pg_restore is faster. > prod_cursor.execute('select data from production') > for each_record in cursor.fetchall(): > dev_cursor.execute('insert into testing') I know, but COPY is much faster. Thomas From dblubaugh at belcan.com Thu Feb 7 13:48:29 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Thu, 7 Feb 2008 13:48:29 -0500 Subject: MyHDL project!! In-Reply-To: <27CC3060AF71DA40A5DC85F7D5B70F38010E3792@AWMAIL04.belcan.com> References: <d9db3974-5e15-4774-8938-24f8718d25ca@y5g2000hsf.googlegroups.com> <27CC3060AF71DA40A5DC85F7D5B70F38010E3792@AWMAIL04.belcan.com> Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F38024F7BF4@AWMAIL04.belcan.com> sir, Is there still a possibility to collaborate??? David Blubaugh -----Original Message----- From: Blubaugh, David A. Sent: Friday, February 01, 2008 10:44 AM To: 'chewie54' Cc: 'python-list at python.org' Subject: MyHDL project !!!!! Dan, I would be honored to start a project such as that in mind. How do we begin ?????? David Blubaugh -----Original Message----- From: chewie54 [mailto:dfabrizio51 at gmail.com] Sent: Thursday, January 31, 2008 9:34 PM To: python-list at python.org Subject: Re: Will Python on day replaceMATLAB????????????????????????????????????????????????????? > I have been evaluating the python environment ever more closer. I > believe I can interface python with a development environment known as > the ImpulseC environment. The ImpulseC environment develops C to VHDL > for FPGA development. I would especially love to interface Python > with ImpulseC and the graphing capabilities of GNU Plot and SciPy in > order to recreate a VHDL development environment that will be just as > capable as a $50,000 dollar Matlab to VHDL toolbox. This is also a > part of my Masters thesis. Is anyone willing to help in this endeavor????? > > David Blubaugh > Why not use MyHDL which is written in Python and translates to Verilog. I assume ImpulseC is a commercial product and costs a log. MyHDL is free. If you have any interests in combining MyHDL with SciPy and NumPy I would be interested in getting involved. Dan Fabrizio This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From bernard.chhun at gmail.com Mon Feb 25 00:15:02 2008 From: bernard.chhun at gmail.com (Bernard) Date: Sun, 24 Feb 2008 21:15:02 -0800 (PST) Subject: most loved template engine on python is? References: <47c1beba$0$381$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <b4c2a196-4ae3-4702-9826-42030e7687d9@b29g2000hsa.googlegroups.com> I've been using Cheetah Template for a year now and loved every bit of it. There's plenty of well written documentation[1] files as well so that you may learn it quick. [1]: http://www.cheetahtemplate.org/learn.html On 24 f?v, 14:01, Tamer Higazi <n... at mail.de> wrote: > Hi people! > After deciding choosing python as my future killer application language > for writing web applications, I need from you guys still some support, > if you apologize. > > Question: > Which is the most loved template engine for python? > > I see, that I can do more aspect oriented programming with python as > with ruby (as comparing those languages). God thanks, I do not have to > create an object for every small thing in python and still generate > classes and access methods statically. > > Tamer From castironpi at gmail.com Sun Feb 24 23:02:55 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 24 Feb 2008 20:02:55 -0800 (PST) Subject: object identity and hashing References: <c4ff37e7-e878-40ca-8bba-e3b002cc9a88@s12g2000prg.googlegroups.com> <-didnQzmJrwavV_anZ2dnUVZ_oOnnZ2d@comcast.com> <6e70c3d2-8656-4077-bc81-2dbfecd5c69b@72g2000hsu.googlegroups.com> <194f1b31-64f1-41fd-b85b-d97e9cdf04ac@62g2000hsn.googlegroups.com> Message-ID: <609bebcf-a9d2-4fdf-952a-38cb80c35567@o77g2000hsf.googlegroups.com> On Feb 24, 9:28?pm, George Sakkis <george.sak... at gmail.com> wrote: > On Feb 24, 9:11 pm, castiro... at gmail.com wrote: > > > > > > > On Feb 24, 7:58 pm, Jeff Schwab <j... at schwabcenter.com> wrote: > > > > castiro... at gmail.com wrote: > > > > Can someone explain this? > > > > >>>> a= {} > > > > Create an empty dict and bind it to the name a. > > > > >>>> a[(3,)]= 0 > > > > Set the key/value pair (3,):0 to the dict. > > > > >>>> (3,) in a > > > > Is (3,) one of the keys in the dict? > > > > > True > > > > Yes, it is. > > > > >>>> (3,) is (3,) > > > > Create two separate tuples (that happen to be equivalent). ?Are they the > > > same object? > > > > > False > > > > No, they are not. > > > > Every time you write (3,), you are potentially creating a new object. > > > These objects have equal values (and hash codes), so they are > > > interchangeable for purposes of keying a dict. > > > I see. ?You stated, > > > > Is (3,) one of the keys in the dict? > > > > > True > > > > Yes, it is. > > > It isn't, but it does equal a key that's already in the dict. > > Right, dict lookup depends on object hashing (__hash__) and equality > (__eq__), not identity. There are legitimate cases where lookup should > be based on identity [1], but they are far less common than those > based on equality. > > George > > [1]http://www.martinfowler.com/eaaCatalog/identityMap.html- Hide quoted text - > > - Show quoted text - [1] illustrates a case in which 'a is a' returns False, and in the other corner of the DeMorgan table, there is 'a is b' returns True for 'a == b' False. From ggpolo at gmail.com Thu Feb 14 06:20:03 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 14 Feb 2008 09:20:03 -0200 Subject: Time line for OJS migration In-Reply-To: <47B3DF32.7060804@acm.org> References: <47AC560C.2060303@acm.org> <43c8685c0802101454h41af1d4cjecbd994c93e4d88e@mail.gmail.com> <47AFA3C2.7050008@acm.org> <ac2200130802110224g2b2e9a1sc6d4b3b4e86a83db@mail.gmail.com> <ac2200130802130526p19195840jc4fd2ded33f18ba9@mail.gmail.com> <47B2F76A.30107@acm.org> <ac2200130802130828m63ddf59ercde15e503e10a678@mail.gmail.com> <ac2200130802130829y2fa09226jfac2b0eeb751c0ca@mail.gmail.com> <ac2200130802130858k2ab4d735o7a61f64360516cf4@mail.gmail.com> <47B3DF32.7060804@acm.org> Message-ID: <ac2200130802140320k379350ecl36be021e587a20b0@mail.gmail.com> 2008/2/14, Maurice Ling <mauriceling at gmail.com>: > Hi Guilherme > > I've seen the site, it looks pretty good. > > Just wondering if you foresee any problems in moving the whole > installation to another server? If not, perhaps you can try to migrate > the documents (instructions for authors etc) to OJS at your end. > > > ML > Well, I never did a OJS migration before but I'm trusting its tool to do the migration later. And just to know.. is OJS going to be the new TPP site ? -- -- Guilherme H. Polo Goncalves From brianmarsh at yahoo.com Wed Feb 6 20:23:35 2008 From: brianmarsh at yahoo.com (pythonbrian) Date: Wed, 6 Feb 2008 17:23:35 -0800 (PST) Subject: Need help with first program to connect to mysql database via apache and python. Message-ID: <ceecc7d3-dc7a-4d1b-b162-cbecf186cbef@q39g2000hsf.googlegroups.com> I am just learning python and I am trying to create a simple connection to a mysql table via Python and Apache, using a Python program Unfortunately I keep getting an internal server error (50), when I bring it up in my browser ... information attached. Any help would be appreciated ... Thx, brianmarsh at yahoo.com Information #1 error in /var/log/apache2/error.log [Wed Feb 06 20:04:31 2008] [error] [client 127.0.0.1] (2)No such file or directory: exec of '/var/www/cgi-bin/fig17_27.py' failed [Wed Feb 06 20:04:31 2008] [error] [client 127.0.0.1] Premature end of script headers: fig17_27.py ----------------------------------------------------------------------- Information #2 directory information brianmarsh at ubuntu:/var/log/apache2$ cd /var/www/cgi-bin brianmarsh at ubuntu:/var/www/cgi-bin$ ls -al total 24 drwxr-xr-x 2 root root 4096 2008-02-06 15:03 . drwxr-xr-x 4 root root 4096 2008-02-02 20:53 .. -rwxr-xr-x 1 root root 1569 2008-02-02 21:02 fig06_03.py -rwxr-xr-x 1 root root 2067 2008-02-02 21:05 fig06_05.py -rwxr-xr-x 1 root root 2031 2008-02-02 21:19 fig06_06.py -rwxr-xr-x 1 root root 3489 2008-02-06 15:03 fig17_27.py ----------------------------------------------------------------------------------------- Web Error http://localhost/cgi-bin/fig17_27.py Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator, webmaster at localhost and inform them of the time the error occurred, and anything you might have done that may have caused the error. More information about this error may be available in the server error log. Apache/2.2.4 (Ubuntu) mod_python/3.3.1 Python/2.5.1 PHP/ 5.2.3-1ubuntu6.3 Server at localhost Port 80 ------------------------------------------------------------------------------ Program File brianmarsh at ubuntu:/var/www/cgi-bin$ cat fig17_27.py #!/usr/local/bin/python # Fig. 17.27: fig17_27.py # Displays contents of the Authors table, # ordered by a specified field. import MySQLdb import cgi import sys def printHeader( title ): print """Content-type: text/html <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xml:lang = "en" lang = "en"> <head><title>%s """ % title # obtain user query specifications form = cgi.FieldStorage() # get "sortBy" value if form.has_key( "sortBy" ): sortBy = form[ "sortBy" ].value else: sortBy = "firstName" # get "sortOrder" value if form.has_key( "sortOrder" ): sortOrder = form[ "sortOrder" ].value else: sortOrder = "ASC" printHeader( "Authors table from Books" ) # connect to database and retrieve a cursor try: connection = MySQLdb.connect( db = "Books", user = "root" ) # error connecting to database except MySQLdb.OperationalError, error: print "Error:", error sys.exit( 1 ) # retrieve cursor else: cursor = connection.cursor() # query all records from Authors table cursor.execute( "SELECT * FROM Authors ORDER BY %s %s" % ( sortBy, sortOrder ) ) allFields = cursor.description # get field names allRecords = cursor.fetchall() # get records # close cursor and connection cursor.close() connection.close() # output results in a table print """\n""" # create table header for field in allFields: print "" % field[ 0 ] print "" # display each record as a row for author in allRecords: print "" for item in author: print "" % item print "" print "
%s
%s
" # obtain sorting method from user print """ \n
Sort By:
""" # display sorting options for field in allFields: print """""" % field[ 0 ] print field[ 0 ] print "
" print """
\nSort Order:
Ascending Descending

\n
\n\n\n""" From dave_mikesell at fastmail.fm Thu Feb 28 23:25:17 2008 From: dave_mikesell at fastmail.fm (dave_mikesell at fastmail.fm) Date: Thu, 28 Feb 2008 20:25:17 -0800 (PST) Subject: Article of interest: Python pros/cons for the enterprise References: Message-ID: Good article. Re: the comparisons with C++, most of my experience is with C++ and I like it because it's powerful, flexible, portable, and keeps me employable. However, I can't think of any application or system I've written in C++ (or Java or Perl) that could not have been written in Python. In my hobbyist work, I've used Python quite a bit and will some more. It's a joy to program with. Love to get a Python gig someday, but there's just not much of a market, and with Ruby on Rails emerging as the next Silver Bullet, I don't see one emerging soon. No worries. C++ and Python will both enjoy long futures. Longer than I will be employed. From bearophileHUGS at lycos.com Sun Feb 10 15:10:19 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 10 Feb 2008 12:10:19 -0800 (PST) Subject: Turn off ZeroDivisionError? References: <63d2e7d1-aa26-4ddc-9d12-42ae636104c1@s37g2000prg.googlegroups.com> Message-ID: <5f7c4c6c-7b0a-471a-b17d-3e5fb24a9e00@y5g2000hsf.googlegroups.com> Mark Dickinson: > This is probably the only sane way to deal with differences in > platform behaviour when doing float divisions. What Python run on a CPU that doesn't handle the nan correctly? Bye, bearophile From nure123 at gmail.com Sat Feb 9 19:44:52 2008 From: nure123 at gmail.com (nure123 at gmail.com) Date: Sat, 9 Feb 2008 16:44:52 -0800 (PST) Subject: What is wrong with this Message-ID: Hi, I am new to Python and would be grateful if anyone could tell me what is wrong with the following statement. Y=array([1/S, 0*lam]) where S=[1, 2, 3, 4] lam=[5, 6, 7, 8] I am using Numeric not the NumPy and the original module in which this statement appears is supposed to be working perfectly fine since an executable based on that module is working fine ( I may be wrong if the original author derived his executable file from a version of module other than the one whose code is distributed) Thanks, Nure From nicola.musatti at gmail.com Fri Feb 22 10:44:05 2008 From: nicola.musatti at gmail.com (Nicola Musatti) Date: Fri, 22 Feb 2008 07:44:05 -0800 (PST) Subject: Article of interest: Python pros/cons for the enterprise References: <2f1527a7-2f66-44c7-9665-4d8ff01fa5ab@28g2000hsw.googlegroups.com> <47bd4a24$0$25225$426a74cc@news.free.fr> <036e93e6-5840-4a3c-8642-67a0a9ec44f2@i7g2000prf.googlegroups.com> <784ec210-f389-4a15-b458-961100de9103@v3g2000hsc.googlegroups.com> <5MSdncqVGdEXiSPanZ2dnUVZ_vPinZ2d@comcast.com> <7xskzldz7l.fsf@ruckus.brouhaha.com> Message-ID: On Feb 22, 3:25 pm, Roy Smith wrote: > In article > , > Nicola Musatti wrote: > > > Yet I'm convinced that even such partial guarantee is worth having. > > Partial guarantees are like being a little bit pregnant. Yes, and I'm sure your tests cover all possible paths through your code. Cheers, Nicola Musatti From python.list at tim.thechases.com Fri Feb 1 07:57:41 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 01 Feb 2008 06:57:41 -0600 Subject: Why the HELL has nobody answered my question !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! In-Reply-To: <47a2bcb3$0$5952$9b4e6d93@newsspool3.arcor-online.net> References: <47a2bcb3$0$5952$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <47A31745.8090906@tim.thechases.com> > I actually expect hell to have the largest computing powers in > the universe. What do you think how many IBM, Solaris, > don't-ask-me-what machines admins have already sent down > there? Seems like they'd have trouble with cooling problems... (okay, I was just told yesterday that "hell is hot" is a culturally relative thing, and that the Nordic version of hell involves extreme cold. ymmv) -tkc From afriere at yahoo.co.uk Mon Feb 18 21:10:55 2008 From: afriere at yahoo.co.uk (Asun Friere) Date: Mon, 18 Feb 2008 18:10:55 -0800 (PST) Subject: Seemingly odd 'is' comparison. References: <47b36135$0$26076$88260bb3@free.teranews.com> <13rk2ho7b8h1c85@corp.supernews.com> Message-ID: <90e29d02-1986-42a4-baa5-1debf44a592a@s13g2000prd.googlegroups.com> On Feb 19, 9:44 am, Steven D'Aprano wrote: > Except for documented singletons such as modules and None, which objects > have the same identity is platform dependent, version dependent, and even > dependent on the execution history of your code. The advice not to identity test strings and numbers (since they are interred in the main implementation), or tuples, since they potentially could be, seems sound enough. But given the nature of mutables, is the identity of these even potentially implementation dependant (ie. they couldn't be interred could they)? One might conceivably want to know that a list into which one is about to stuff something is the same (or perhaps not the same) list as that pointed to by another name, which operation, hopefully, remains possible across the range of potential implementations. From BjornSteinarFjeldPettersen at gmail.com Mon Feb 11 08:04:53 2008 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Mon, 11 Feb 2008 05:04:53 -0800 (PST) Subject: Is there an easy way to sort a list by two criteria? References: <902c5105-c85d-4ba5-8c9f-0dd5061cef9e@b2g2000hsg.googlegroups.com> <492e8201-13d6-40d9-b8ba-23f7af781946@m34g2000hsb.googlegroups.com> <401b9a8b-c5c1-4e4e-b70e-8f40d2870f1b@i7g2000prf.googlegroups.com> Message-ID: On Feb 11, 10:47 am, bearophileH... at lycos.com wrote: [...] > A little known thing from Python 2.5: [...] > >>> sorted(lst, key=itemgetter(2, 1)) Cute, thanks :-) --bjorn From Matthew_WARREN at bnpparibas.com Tue Feb 5 12:14:19 2008 From: Matthew_WARREN at bnpparibas.com (Matthew_WARREN at bnpparibas.com) Date: Tue, 5 Feb 2008 17:14:19 +0000 Subject: Why chdir command doesn't work with client.get_transport() ? In-Reply-To: <15248798.post@talk.nabble.com> Message-ID: As other have said, it's because exec_command uses a new session each time. You may get some joy with this, untested exec_command('cd /some/where; somecommand') uses the semi-colon to separate multiple commands on one command line. Matt. Internet charles_hans at yahoo.com To python-list Sent by: cc python-list-bounces+matthew.warren=uk.bnpparibas.com@ python.org Subject Why chdir command doesn't work with 02/02/2008 23:41 client.get_transport() ? I am new to paramiko. I wrote a script to copy files between Solaris and XP machines as below: import paramiko def exec_command(trans, command): chan = trans.open_session() chan.exec_command(command) stdin = chan.makefile('wb') stdout = chan.makefile('rb') stderr = chan.makefile_stderr('rb') return stdin, stdout, stderr def main(): client = paramiko.SSHClient() client.connect(hostname, username=username, password=password) trans = client.get_transport() dummy_chan = trans.open_session() exec_command(trans, 'cd temp') stdin, stdout, stderr = exec_command(pwd) >From the last line I found from stdout that the pwd is not changed. I tried to type the full path in 'cd', did not help. Other UNIX commands such as ls, mkdir, cp, rm will work. Only this 'cd' never works. I got stuck here. Please help. Thanks! Charles 2/2 -- View this message in context: http://www.nabble.com/Why-chdir-command-doesn%27t-work-with-client.get_transport%28%29---tp15248798p15248798.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list This message and any attachments (the "message") is intended solely for the addressees and is confidential. If you receive this message in error, please delete it and immediately notify the sender. Any use not in accord with its purpose, any dissemination or disclosure, either whole or partial, is prohibited except formal approval. The internet can not guarantee the integrity of this message. BNP PARIBAS (and its subsidiaries) shall (will) not therefore be liable for the message if modified. Do not print this message unless it is necessary, consider the environment. --------------------------------------------- Ce message et toutes les pieces jointes (ci-apres le "message") sont etablis a l'intention exclusive de ses destinataires et sont confidentiels. Si vous recevez ce message par erreur, merci de le detruire et d'en avertir immediatement l'expediteur. Toute utilisation de ce message non conforme a sa destination, toute diffusion ou toute publication, totale ou partielle, est interdite, sauf autorisation expresse. L'internet ne permettant pas d'assurer l'integrite de ce message, BNP PARIBAS (et ses filiales) decline(nt) toute responsabilite au titre de ce message, dans l'hypothese ou il aurait ete modifie. N'imprimez ce message que si necessaire, pensez a l'environnement. From gagsl-py2 at yahoo.com.ar Mon Feb 18 02:55:53 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 18 Feb 2008 05:55:53 -0200 Subject: How to get current module object References: <47B87C28.3030302@gmail.com> Message-ID: En Sun, 17 Feb 2008 16:25:44 -0200, Alex escribi?: > Can I get reference to module object of current module (from which the > code is currently executed)? I know __import__('filename') should > probably do that, but the call contains redundant information (filename, > which needs to be updated), and it'll perform unnecessary search in > loaded modules list. > > It shouldn't be a real problem (filename can probably be extracted from > the traceback anyway), but I wonder if there is more direct and less > verbose way. sys.modules[__name__] Why do you want to get the module object? globals() returns the module namespace, its __dict__, perhaps its only useful attribute... -- Gabriel Genellina From Frank.Aune at broadpark.no Wed Feb 6 10:04:25 2008 From: Frank.Aune at broadpark.no (Frank Aune) Date: Wed, 6 Feb 2008 16:04:25 +0100 Subject: Must COMMIT after SELECT (was: Very weird behavior in MySQLdb "execute") In-Reply-To: <47a8a25a$0$36337$742ec2ed@news.sonic.net> References: <47a76661$0$36336$742ec2ed@news.sonic.net> <47a8a25a$0$36337$742ec2ed@news.sonic.net> Message-ID: <200802061604.26105.Frank.Aune@broadpark.no> On Tuesday 05 February 2008 18:58:49 John Nagle wrote: > So you really do have to COMMIT after a SELECT, if you are reusing > the database connection. CGI programs usually don't have this issue, > because their connections don't live long, but long-running FCGI (and maybe > Twisted) programs do. I've experienced the same thing for long-running tasks even when using different connections/cursors against the same db for db queries and log writing dbhandlers respectively. Whenever I did a SELECT() on the first connection, the cursor would stop "seeing" new entries commited in the log table by the other connection. I always assumed you needed COMMIT() after adding new content to the database, not after every single query, but this perhaps indicate otherwise? Regards, Frank From pavlovevidence at gmail.com Thu Feb 21 21:04:41 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 21 Feb 2008 18:04:41 -0800 (PST) Subject: Article of interest: Python pros/cons for the enterprise References: <47BC31EF.3080107@tim.thechases.com> Message-ID: On Feb 21, 11:17 am, "Reedick, Andrew" wrote: > So I wouldn't be > quick to dismiss the notion that Java/C#/C++ are more newbie-safe than > Python. =/ FWIW, when I posted my comment about C++, I was mocking the article writer's notion that it was static typing and compile-time checking that made Java and C# "safer" for newbies, by presenting an example that clearly defied that. I was taking it for granted the C++ is notoriously dangerous and newbie-unfriendly. Obviously it is not a universal opinion (yet). Too bad. But all I was really saying is that there are far more more important things when it comes to "safety" than dynamic typing. Carl Banks From http Tue Feb 12 15:32:43 2008 From: http (Paul Rubin) Date: 12 Feb 2008 12:32:43 -0800 Subject: Recursive generator References: Message-ID: <7x63wt5310.fsf@ruckus.brouhaha.com> Paul Hankin writes: > def genDescendants(self): > return chain([self], *[child.genDescendants() > for child in self.children]) That is scary. It generates an in-memory list the size of the whole subtree, at every level. Total memory consumption is maybe even quadratic, depending on the tree shape, but even if it's only linear, it's way ugly. From stefan_ml at behnel.de Thu Feb 28 15:53:02 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 28 Feb 2008 21:53:02 +0100 Subject: XML expat error In-Reply-To: <52c4ac7c-3d47-43c0-a24d-8f8dfbbf08a6@s8g2000prg.googlegroups.com> References: <5fb056d5-55fe-43c8-83f6-54b65da3860d@u69g2000hse.googlegroups.com> <62n5ipF23jpgaU2@mid.uni-berlin.de> <52c4ac7c-3d47-43c0-a24d-8f8dfbbf08a6@s8g2000prg.googlegroups.com> Message-ID: <47C71F2E.2060804@behnel.de> dirkheld wrote: > On 28 feb, 08:18, Marc 'BlackJack' Rintsch wrote: >> On Wed, 27 Feb 2008 14:02:25 -0800, dirkheld wrote: >>> Something strange here. The xml file causing the problem has only 361 >>> lines. Isn't there a way to catch this error, ignore it and continu >>> with the rest of the other files? >> Yes of course: handle the exception instead of letting it propagate to the >> top level and ending the program. >> >> Ciao, >> Marc 'BlackJack' Rintsch > > Ehm, maybe a stupid question... how. I'm rather new to python and I > never user error handling. Care to read the tutorial? Stefan From roland.hedberg at adm.umu.se Tue Feb 5 03:17:41 2008 From: roland.hedberg at adm.umu.se (Roland Hedberg) Date: Tue, 05 Feb 2008 09:17:41 +0100 Subject: Any python implementation of XML-DSIG ? Message-ID: <47A81BA5.6020503@adm.umu.se> Or is XMLsig for Dynamic Languages (Ruby, Python, PHP and Perl) at http://xmlsig.sourceforge.net/ the only option ? -- Roland From larry.bates at websafe.com Wed Feb 20 12:21:31 2008 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 20 Feb 2008 11:21:31 -0600 Subject: Handling locked db tables... In-Reply-To: References: <6768beab-566e-4d0e-94c9-a4def273d467@m23g2000hsc.googlegroups.com> Message-ID: <1lZuj.102852$K27.51612@bignews6.bellsouth.net> breal wrote: > On Feb 20, 8:05 am, "M.-A. Lemburg" wrote: >> On 2008-02-20 16:24, breal wrote: >> >>> I have a db table that holds a list of ports. There is a column >>> in_use that is used as a flag for whether the port is currently in >>> use. When choosing a port the table is read and the first available >>> port with in_use = 0 is used, updated to in_use = 1, used, then >>> updated to in_use = 0. I am using MySQLdb and want to make sure I am >>> locking the table when doing reads, writes, updates since there will >>> be several instances of my program looking for available ports >>> simultaneously. >>> When I run a "lock table mytable read" I can do all of my >>> transactions. But, when another cursor then tries to do the read I >>> get an error unless the first process has been completed... unlocking >>> the tables. How is this handled generally? >> This is normal database locking behavior. If you do an update to >> a table from one process, the updated row is locked until the >> transaction is committed. >> >> If another process wants to access that row (even if only indirectly, >> e.g. a select that does a query which includes the data from the locked >> row), that process reports a database lock or times out until the >> lock is removed by the first process. >> >> The reason is simple: you don't want the second process to report >> wrong data, since there's still a chance the first process might >> roll back the transaction. >> >> Most modern database allow row-level locking. I'm not sure whether >> MySQL supports this. SQLite, for example, only support table locking. >> >> -- >> Marc-Andre Lemburg >> eGenix.com >> >> Professional Python Services directly from the Source (#1, Feb 20 2008)>>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>>>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ >> ________________________________________________________________________ >> >> :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: >> >> eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 >> D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg >> Registered at Amtsgericht Duesseldorf: HRB 46611 > > Marc-Andre, > > Thanks for the reply. I understand that this is normal locking > behavior. What I am looking for is a standard method to either loop > the query until the table is unlocked, or put the query into some sort > of queue. Basically my queries work like this. > > Request comes in > > PART I: > LOCK TABLE port_usage READ; > SELECT * FROM port_usage WHERE in_use = 0; > Get available port > UPDATE port_usage SET in_use = 1 WHERE port = available_port; > UNLOCK TABLES; > > send request to available port and do some stuff until finished with > port > > PART II: > LOCK TABLE port_usage READ > UPDATE port_usage SET in_use = 0 WHERE port = available_port; > UNLOCK TABLES; > > Several of these *may* be happening simultaneously so when a second > request comes in, and the first one has the table locked, I want to > have the PART I sql still work. Any suggestions here? > I think you want to use SELECT for UPDATE or SELECT LOCK IN SHARE MODE. Here is a link that might help: http://dev.mysql.com/doc/refman/5.1/en/innodb-locking-reads.html -Larry From bearophileHUGS at lycos.com Mon Feb 25 17:25:34 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 25 Feb 2008 14:25:34 -0800 (PST) Subject: PyEuler References: <9e435ab2-3323-4ad9-9dd9-cdde34c3fb91@e25g2000prg.googlegroups.com> <7x1w70x2hd.fsf@ruckus.brouhaha.com> Message-ID: <0a552b42-69f0-492f-9357-38ad5226c4ed@d4g2000prg.googlegroups.com> Paul Rubin: > def ggenfib(): > a,b = 1,2 > while True: > yield a > a,b = b, a=b Your version is the nice basic generator version (the last line contains a +, I presume), but I like this other version too: def xfibonacci(): a = b = 1 yield a yield b while True: a = a + b yield a b = b + a yield b It's a bit faster, longer, and I find it a bit more readable. > There is a full set of solutions on the haskell wiki, if anyone cares. Thank you for the suggestion, I have found it: http://www.haskell.org/haskellwiki/Euler_problems In the last months lot of people are suddenly talking about Haskell (and sometimes even F#!). I think the Haskell language is too much complex for me for bigger programs, but for such small mathematical programs it looks very nice and almost readable. This is a curious comment from that Wiki about a solution to the Problem 2: >The first two solutions work because 10^6 is small. The following solution also works for much larger numbers (up to at least 10^1000000 on my computer):< What I like of the Haskell community is how much they keep things tidy and ordered. And every function used on the Wiki points to the documentation! They create a spotless wiki about Shootout benchmarks, Euler problems, and so on, they discuss al lot and they try to find fast & correct solutions. They even *improve* their language when they find some benchmarks of the Shootout run too much slow with Haskell, because they have understood that despite being most little (silly) programs, the benchmarks of the Shootout site are rather well thought out. Both the Python and D communities that I know (and I appreciate) aren't like that. I presume the Haskell language itself appeals to people that like tidy and well ordered things, and when you use that language a lot it may encourage your mind to think even more in that way. Computer languages too make the man :-) Bye, bearophile From deets at nospam.web.de Sun Feb 17 15:48:12 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 17 Feb 2008 21:48:12 +0100 Subject: Linux/Python Issues In-Reply-To: References: Message-ID: <61rkskF200tihU1@mid.uni-berlin.de> MartinRinehart at gmail.com schrieb: > I went to Python.org, DL'd Python 2.5 source code per the usual > inadequate instructions and ran the make files successfully (sort of). > Python 2.5 works fine. But "from Tkinter import *" gets a "What's > Tkinter?" message. IDLE's no where to be found. > > What's not in the instructions is what directory should I be in when I > download? Where should I put the ".bz2" file? What dir for running the > make files? At present I'm working on a Windows machine, endangering > what's left of my sanity. > > I'm using Linspire, so Debian directories are probably the ones that > will get me up and running. Barring specific knowledge, even some good > guesses would be appreciated. Nothing special, just reading the "configure --help" will help you. You need Tcl/Tk + possible devel-packages so the header-files are found. I'm not an expert on the required versions, but that should be told you somewhere. But I doubt that there isn't a python2.5 already available for your distro - especially if it's debian based. Ubuntu for example has 2.5 as default. Diez From Lie.1296 at gmail.com Sat Feb 16 14:17:05 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 16 Feb 2008 11:17:05 -0800 (PST) Subject: How about adding rational fraction to Python? References: <6eba298e-6888-462a-afa7-54fae02c3dce@y5g2000hsf.googlegroups.com> <61ibo1F1uqso2U1@mid.uni-berlin.de> <188be6e9-bc05-4a72-924b-1de184980002@n58g2000hsf.googlegroups.com> <9b166b3d-89df-4f26-956a-abbd391167e7@i12g2000prf.googlegroups.com> <13rcd3nskgpv91d@corp.supernews.com> <13rde22ktgpu532@corp.supernews.com> <26641b5f-d6cb-45a6-8736-7d130d1a5aee@u10g2000prn.googlegroups.com> Message-ID: <3aca9bf7-5342-4ac8-bbfe-6c64f63434a5@s8g2000prg.googlegroups.com> On Feb 17, 1:40?am, Jeff Schwab wrote: > Lie wrote: > > Would all these problems with floating points be a rational reason to > > add rational numbers support in Python or Py3k? (pun not intended) > > > I agree, there are some numbers that is rationals can't represent > > (like pi, phi, e) but these rounding problems also exist in floating > > points, and rational numbers wouldn't be so easily fooled by something > > like 1 / 3 * 3, and 1/10 (computer) is exactly 0.1 (human). The first > > problem with rational is that to get an infinite precision rational, > > the language would have to have an infinite length integers, which > > Python have given us. The second problem with rationals is to keep > > rationals in its most simple, trivial form. This can be solved with a > > good GCD algorithm, which can also be a nice addition to Python's math > > library. > > http://www.python.org/dev/peps/pep-0239/ Yes, I'm aware of the PEP and actually have been trying for some time to reopen the PEP. The reason that PEP is rejected is because Decimal is accepted, which I think is a completely absurd reason as Decimal doesn't actually solve the rounding problems and equality comparison problem. Some people have also pointed out that Decimal IS Inexact, while a rational number is always exact except if you have an operation with a (binary or decimal) floating point involved (this can be easilty resolved by making fraction recessive, i.e. an operation that receive a fraction and a float should return a float). From gagsl-py2 at yahoo.com.ar Tue Feb 19 05:47:05 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 19 Feb 2008 02:47:05 -0800 (PST) Subject: average of PIL images References: Message-ID: On 19 feb, 06:28, vaneric wrote: > > > def rgbTopixelvalue((r,g,b)): > > > ? ?alpha=255 > > > ? ?return unpack("l", pack("BBBB", b, g, r, alpha))[0] > > > That's much worse than averaging the R,G,B components. > > oops! > the intention was to pack r,g,b components into a single value sothat > calculations like finding covariant matrix of a set of images etc can > be done..(i need to represent each image as an array of ?values(either > long or float)..i can't work with an array of tuples of ints.. > > > As said above, try to compute using another color space, try HSL. The > > colorsys module can transform from/to RGB. > > even if i convert from rgb to hsl i will have a tuple(h,s,l) for each > pixel and again i will have to convert it into a single value which i > can use in matrix multipln etc > > is there a workaround sothat rgb color images can be worked on? any > advice most welcome.. a) Work with the 3 components in parallel (that is, use 3 separate matrices, one for each component, and regenerate the image at the end). b) Convert to grayscale (and lose the color information) -- Gabriel Genellina From cfbolz at gmx.de Wed Feb 20 05:11:48 2008 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Wed, 20 Feb 2008 11:11:48 +0100 Subject: Current Fastest Python Implementation? In-Reply-To: <8b977c84-6591-45b2-9454-908f338ff509@p73g2000hsd.googlegroups.com> References: <728901d3-edb8-4c7a-b823-7065a9b1250e@e6g2000prf.googlegroups.com> <47B943C8.1060805@behnel.de> <8b977c84-6591-45b2-9454-908f338ff509@p73g2000hsd.googlegroups.com> Message-ID: <47BBFCE4.8060309@gmx.de> cokofreedom at gmail.com wrote: > On Feb 18, 9:37 am, Stefan Behnel wrote: >> samuraisam wrote: >>> Has anyone done any recent testing as to which current python >>> implementation is the quickest? >> Search for a recent thread on CPython and IronPython. >> >>> Perhaps for Django development - >>> though the current one certainly is fast (and I doubt micro >>> optimizations would make much difference in overall performance). >>> Regardless - have those pypy folks made a faster implementation, or >>> the jython folks? Or the .NET implementation? >> Depends on your use case. Take your application, do some benchmarking and use >> the implementation that turns out to be a) most reliable and b) the fastest. >> >> In that order. That's very good advice. Basically all four of those Python implementations have situations where they are faster than all the others. I guess CPython (possibly using Psyco) is still faster in many cases, but it really depends on your application. > PyPy [http://codespeak.net/pypy/dist/pypy/doc/home.html] is getting > progressively faster. This is true ? PyPy is slowly getting faster. We have two students working explicitly on speed right now: Anto Cuni is doing a phd thesis on speeding up PyPy's Python interpreter when compiled to .NET and I am doing a Master thesis on improving the JIT of PyPy. > In fact for certain things it can be faster than C [http:// > morepypy.blogspot.com/2008/01/rpython-can-be-faster-than-c.html]! This link is misleading, since it is about the speed of RPython when translated to C, not normal Python programs. Normal Python programs tend to be not RPython, so that figure is hardly interesting. > However it seems it still has a way to go to be fully operational! > Still looks like the future to me. Cheers, Carl Friedrich Bolz From gagsl-py2 at yahoo.com.ar Tue Feb 19 14:08:21 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 19 Feb 2008 11:08:21 -0800 (PST) Subject: Py_Finalize ERROR! References: Message-ID: <04ae8b26-3b76-46fd-bf4e-e068947923db@u72g2000hsf.googlegroups.com> On 19 feb, 05:11, zaley wrote: > Py_Finalize ERROR! > > In my C++ program ,python is embeded . I create one win thread to run > embedded Python code . > So at the begin of thread function I call "Py_Initialize" and at the > end of thread function call "Py_Finalize" . > But after I began thread several times,the program crashed ?in > function ?"Py_Finalize". > I can see the error occured at function "PyObject_ClearWeakRefs" when > "Py_Finalize" called "type_dealloc"; > > Note: the python25.dll(lib) is builded by VC6(SP6) Try to not call repeatedly Py_Initialize/Py_Finalize, only at the start/end of your program. If only one thread is running Python at the same time I *think* you don't have to do any special handling. -- Gabriel Genellina From python.list at tim.thechases.com Wed Feb 13 20:16:31 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 13 Feb 2008 19:16:31 -0600 Subject: Complicated string substitution In-Reply-To: <665bbc19-bebd-4633-adf5-4650e342544d@z17g2000hsg.googlegroups.com> References: <665bbc19-bebd-4633-adf5-4650e342544d@z17g2000hsg.googlegroups.com> Message-ID: <47B3966F.6030407@tim.thechases.com> > I have a file with a lot of the following ocurrences: > > denmark.handa.1-10 > denmark.handa.1-12344 > denmark.handa.1-4 > denmark.handa.1-56 Each on its own line? Scattered throughout the text? With other content that needs to be un-changed? With other stuff on the same line? > denmark.handa.1-10_1 > denmark.handa.1-12344_1 > denmark.handa.1-4_1 > denmark.handa.1-56_1 > > so basically I add "_1" at the end of each ocurrence. > > I thought about using sed, but as each "root" is different I have no > clue how to go through this. How are the roots different? Do they all begin with "denmark.handa."? Or can the be found by a pattern of "stuff period stuff period number dash number"? A couple sed solutions, since you considered them first: sed '/denmark\.handa/s/$/_1/' sed 's/denmark\.handa\.\d+-\d+/&_1/g' sed 's/[a-z]+\.[a-z]+\.\d+-\d+/&_1/g' Or are you just looking for "number dash number" and want to suffix the "_1"? sed 's/\d+-\d+/&_1/g' Most of the sed versions translate pretty readily into Python regexps in the .sub() call. import re r = re.compile(r'[a-z]+\.[a-z]+\.\d+-\d+') out = file('out.txt', 'w') for line in file('in.txt'): out.write(r.sub(r'\g<0>_1', line)) out.close() Tweak the regexps accordingly. -tkc From mr.cerutti at gmail.com Fri Feb 1 09:44:25 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Fri, 1 Feb 2008 09:44:25 -0500 Subject: How to identify which numbers in a list are within each others' range In-Reply-To: <073ebb96-3572-4aa5-88d6-53e97cc55633@c4g2000hsg.googlegroups.com> References: <6b4ac79b-6267-438d-8b28-aa4bba78a586@i3g2000hsf.googlegroups.com> <1ffed8a2-f00b-4913-802f-b2cc9fa0ab19@i12g2000prf.googlegroups.com> <073ebb96-3572-4aa5-88d6-53e97cc55633@c4g2000hsg.googlegroups.com> Message-ID: <51302a8c0802010644l2bc7d2b2u7d05c52b162c576e@mail.gmail.com> On Feb 1, 2008 8:28 AM, Arnaud Delobelle wrote: > Yours is O(n^2) and \Omega(n^2). I think mine is O(max(c, nlogn)) > (assuming constant time access for dictionaries, but 'inside' could be > replaced with a list) where c is the number of overlaps. I'll try to > post a proof later (if it's true!). So if we are in a situation where > overlaps are rare, it is in practice O(nlogn). Here's another contender, basically the same as yours, but spelled without iterators. def overlaps(eranges): """Determine, from a list of numbers and a +/- range of uncertainty, which number ranges overlap each other. Return the overlapping range indexes as a list of overlapping pairs. >>> sorted(overlaps(((55, 3), (20, 2), (17, 4), (60, 3)))) [(0, 3), (1, 2)] """ d = [(r[0] - r[1], r[0] + r[1], i) for i, r in enumerate(eranges)] d.sort() rv = [] x = 0 while x < len(d): minx, maxx, ix = d[x] y = x+1 while y < len(d): miny, maxy, iy = d[y] if miny < maxx: rv.append((ix, iy) if ix < iy else (iy, ix)) else: break y += 1 x += 1 return rv -- Neil Cerutti From grante at visi.com Fri Feb 8 12:45:36 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 08 Feb 2008 17:45:36 -0000 Subject: Why not a Python compiler? References: <28eead2f-a40c-414b-bd3d-a941f8a851a2@d70g2000hsb.googlegroups.com> <81339c25-f9b6-47a1-941e-8ae39c35773c@e6g2000prf.googlegroups.com> <98a1bc2d-290b-4b6d-8a3d-eda7666d2b8b@l1g2000hsa.googlegroups.com> <13qmtu5j1b1p6a2@corp.supernews.com> <8763x0fix1.fsf@mulj.homelinux.net> Message-ID: <13qp5a02t36def9@corp.supernews.com> On 2008-02-08, Arnaud Delobelle wrote: >> the compiler could do little else except translate it to something >> like: >> >> (python:add a b) > [snip more interesting considerations about compiling python] > > Please get back on topic. This discussion is about parsecs and > wookies now. What's a "wookie" a unit of? -- Grant Edwards grante Yow! Am I accompanied by a at PARENT or GUARDIAN? visi.com From rocksportrocker at googlemail.com Wed Feb 27 09:57:59 2008 From: rocksportrocker at googlemail.com (rocksportrocker) Date: Wed, 27 Feb 2008 06:57:59 -0800 (PST) Subject: BaseHTTPServer and do_POST method References: <0215927e-0d35-4b97-b5b1-bc46cd6f3b88@64g2000hsw.googlegroups.com> <2fdc85df-f830-45db-a313-87f4d89c1803@h11g2000prf.googlegroups.com> <9ecdcfee-66b0-47d7-b896-9b1445865b99@u72g2000hsf.googlegroups.com> Message-ID: <903017fb-3573-40ef-9b75-52bd57d0687f@f47g2000hsd.googlegroups.com> If I ommit send_response() in do_POST() I get no errormessage. That is an acceptable solution for me. Greetings, Uwe From kwa at kuwata-lab.com Sun Feb 24 22:54:11 2008 From: kwa at kuwata-lab.com (makoto kuwata) Date: Sun, 24 Feb 2008 19:54:11 -0800 (PST) Subject: most loved template engine on python is? References: <47c1beba$0$381$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <4bb6cf43-751a-4a42-be77-8d6652d8c24b@z70g2000hsb.googlegroups.com> On 2008-02-25 Tamer Higazi wrote: > Question: > Which is the most loved template engine for python? > I recommend pyTenjin template engine. http://www.kuwata-lab.com/tenjin/ pyTenjin is not famous nor popular, but it is very fast, full- featured, and very easy-to-use. The above web page shows that pyTenjin is about 3 times faster than Cheetah, 9 times faster than Django, and 60 times faster than Kid. It is easy to install pyTenjin because it is only single file. users-gude: http://www.kuwata-lab.com/tenjin/pytenjin-users-guide.html examples: http://www.kuwata-lab.com/tenjin/pytenjin-examples.html -- regards, makoto kuwata From pnrdnz at gmail.com Fri Feb 1 16:47:02 2008 From: pnrdnz at gmail.com (pnrdnz at gmail.com) Date: Fri, 1 Feb 2008 23:47:02 +0200 Subject: help with apache + mod_python on mac os x Message-ID: <893f96d0802011347x38891c9dqa7b293340bd1dd88@mail.gmail.com> Hi, I am new on everything about web development. I did many things to get the error at the end. My system has Apache 1.3 by default. I could install Apache 2.2 with no problem. I had to change all binaries in /usr/bin and /usr/sbin to new apache binaries. All ok. System came with python 2.3.1. I removed everything related to 2.3.1 and installed python 2.5.1. Then compiled mod_python successfully with parameters: ./configure --apxs=/usr/sbin/apxs --python=/usr/bin/python make sudo make install sudo make install_dso $ python -V Python 2.5.1 $ strings /usr/local/apache2/modules/mod_python.so => python_init mod_python/3.3.1 2.5.1 $ env |grep PATH PATH=/Library/Frameworks/Python.framework/Versions/Current/bin:/bin:/sbin:/usr/bin:/usr/sbin $ sudo apachectl start httpd: Syntax error on line 54 of /usr/local/apache2/conf/httpd.conf: Cannot load /usr/local/apache2/modules/mod_python.so into server: Library not loaded: /System/Library/Frameworks/Python.framework/Versions/2.3/Python\n Referenced from: /usr/local/apache2/modules/mod_python.so\n Reason: image not found /usr/sbin/apachectl start: httpd could not be started How is it possible that LoadModule still seek at path Versions/2.3 ? Regards, Deniz -------------- next part -------------- An HTML attachment was scrubbed... URL: From bbxx789_05ss at yahoo.com Sun Feb 3 22:36:15 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Sun, 3 Feb 2008 19:36:15 -0800 (PST) Subject: type, object hierarchy? Message-ID: <814a05b4-6f13-4c86-8c68-a30da06ca093@b2g2000hsg.googlegroups.com> print dir(type) #__mro__ attribute is in here print dir(object) #no __mro__ attribute class Mammals(object): pass class Dog(Mammals): pass print issubclass(Dog, type) #False print Dog.__mro__ --output:-- (, , ) The output suggests that Dog actually is a subclass of type--despite the fact that issubclass(Dog, type) returns False. In addition, the output of dir(type) and dir(object): ['__base__', '__bases__', '__basicsize__', '__call__', '__class__', '__cmp__', '__delattr__', '__dict__', '__dictoffset__', '__doc__', '__flags__', '__getattribute__', '__hash__', '__init__', '__itemsize__', '__module__', '__mro__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__subclasses__', '__weakrefoffset__', 'mro'] ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__'] suggests that type inherits from object since type has all the same attributes as object plus some additional ones. That seems to indicate a hierarchy like this: object | V type | V Mammals | V Dog But then why does issubclass(Dog, type) return False? From belred at gmail.com Sat Feb 9 13:57:44 2008 From: belred at gmail.com (belred at gmail.com) Date: Sat, 9 Feb 2008 10:57:44 -0800 (PST) Subject: dependency order Message-ID: i'm having trouble trying to figure this out... it's part of a build system i'm writing in python. maybe someone has a good simple way to solve this. i'm trying to create a dependency order out of multiple lists. list1: B C list2: A B list3: A C i want the end result to be the list: A B C i'm very frustrated that i can't come up with anything that always works. thanks... any clues to solve this would be greatly appreciated. bryan From agenkin at gmail.com Wed Feb 6 17:01:42 2008 From: agenkin at gmail.com (agenkin at gmail.com) Date: Wed, 6 Feb 2008 14:01:42 -0800 (PST) Subject: Looking for library to estimate likeness of two strings Message-ID: <86e63d06-124e-49e8-82e2-dfbea01fcce7@v17g2000hsa.googlegroups.com> Are there any Python libraries implementing measurement of similarity of two strings of Latin characters? I'm writing a script to guess-merge two tables based on people's names, which are not necessarily spelled the same way in both tables (especially the given names). I would like some function that would help me make the best guess. Many thanks in advance! From cwitts at gmail.com Wed Feb 13 13:55:58 2008 From: cwitts at gmail.com (Chris) Date: Wed, 13 Feb 2008 10:55:58 -0800 (PST) Subject: Cannot understand error message References: <215d3d59-2204-44b0-bfdb-c7de8fb1f12f@e23g2000prf.googlegroups.com> Message-ID: It doesn't like all that text in the previous one... Just before s = '' you have 4 double quotes to close to doc-string instead of 3. From castironpi at gmail.com Fri Feb 29 12:24:08 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 29 Feb 2008 09:24:08 -0800 (PST) Subject: call by reference howto???? References: <47c5f9b8$0$21935$9b4e6d93@newsspool2.arcor-online.net> <492dbd31-6f65-4f36-b7af-acf42cf39d7d@34g2000hsz.googlegroups.com> Message-ID: <32a32af2-2d96-4a4e-9e8d-9c21ae5b6557@41g2000hsc.googlegroups.com> On Feb 29, 8:12?am, Steve Holden wrote: > castiro... at gmail.com wrote: > > On Feb 29, 5:56 am, Steve Holden wrote: > >> castiro... at gmail.com wrote: > >>> On Feb 27, 6:02 pm, Tamer Higazi wrote: > >>>> Hi! > >>>> Can somebody of you make me a sample how to define a function based on > >>>> "call by reference" ??? > >>>> I am a python newbie and I am not getting smart how to define functions, > >>>> that should modify the variable I passed by reference. > >>>> thanks in advance > >>>> Tamer > >>> If it's a mutable object, avoid the pitfalls of rebinding the > >>> parameter, and just modify the object. > >>> BAD: > >>> def f( a ): > >>> ? ?a= { 'this': 'that' } > >>> GOOD: > >>> def f( a ): > >>> ? ?a.clear() > >>> ? ?a[ 'this' ]= 'that' > >> BETTER: > > >> class Thang: pass > > >> def f(a): > >> ? ? ?a.this = "that" > > >> thang = Thang() > >> f(thang) > > [please refrain from quoting signatures in your replies] > [better still, use a mailer that omits them from the quote!] > > >> - Show quoted text - > > > What does __coerce__ look like, so you could operate on a.this without > > accessing 'this' member every time? ?For numbers maybe, but what about > > __getattr__( self, name ): return getattr( self.this, name ) for > > strings? ?Then thang.this= "that"; thang.find( 'at' ) -> > > thang.this.find( 'at' ). ?Awesome! > > Where did __coerce__ come from? Stick with the main party, please. > > __coerce__ is an old mechanism intended to be used to bring numeric > types into alignment, and AFAICS has nothing at all to do with whatever > idea you are suggesting. > > As near as I can make out you appear to want to have thang delegate > certain of its method to thang.this. The easiest way to do that would be > to implement a __getattr__() in the Thang class to do so, but remember > that it won't be called for cases where the class has a real attribute > with the correct name. In your example, > class Thang: pass > > def f(a): > a.this = "that" > > thang = Thang() > f(thang) Thang -wasn't- doing anything else. It can delegate everything. (Thang& operator=( const Thang& );.) Then there's __getattribute__, which is called unconditionally, just in case you implement something in Thang besides 'this' on accident. From duncan.booth at invalid.invalid Tue Feb 19 05:18:24 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 Feb 2008 10:18:24 GMT Subject: Garbage collection References: Message-ID: Jarek Zgoda wrote: > Duncan Booth napisa?(a): > >> Pretty much. If you have a __del__ method on an object then in the >> worst case the only thing that can be guaranteed is that it will be >> called zero, one or more than one times. (Admittedly the last of >> these only happens if you work at it). >> >> If it is called then is may be either immediately the last reference >> to the object is lost, or it may be later when the garbage collector >> runs (and not necessarily the first next time the garbage collector >> runs). > > Java finalizers are not called upon VM exit, only when object is swept > by GC (for example when the object is destroyed upon program exit), > the CPython docs read that this is the case for Python too. Is this > behaviour standard for all VM implementations or is > implementation-dependent (CPython, Jython, IronPython)? > Yes, CPython does reference counting so it can call __del__ immediately an object is unreferenced. The GC only comes into play when there is a reference loop involved. If an object is directly involved in a reference loop then __del__ is not called for that object, but a loop could reference another object and its __del__ would be called when the loop was collected. Other Python implementations may behave differently: presumably Jython works as for Java (but I don't know the details of that), and IronPython uses the CLR which has its own peculiarities: finalizers are all called on a single thread which is *not* the thread used to construct the object, so if you use finalizers in a CLR program your program is necessarily multi-threaded with all that implies. Also it takes at least two GC cycles to actually release memory on a CLR object with a finalizer, on the first cycle objects subject to finalization are simply added to a list (so are again referenceable), on the second cycle if the finalizer has completed and the object is unreferenced it can be collected. CLR finalizers also have the interesting quirk that before the finalizer is called any references the object has to other objects are cleared: that allows the system to call finalizers in any order. Otherwise I think the behaviour on exit is pretty standard. If I remember correctly there is a final garbage collection to give finalizers a chance to run. Any objects which become newly unreferenced as a result of that garbage collection will have __del__ called as usual, but any which merely become unreachable and therefore would be caught in a subsequent garbage collection won't. From mentaltruckdriver at gmail.com Thu Feb 28 21:20:26 2008 From: mentaltruckdriver at gmail.com (mentaltruckdriver at gmail.com) Date: Thu, 28 Feb 2008 18:20:26 -0800 (PST) Subject: (Newbie) Help with sockets. Message-ID: <146eb331-a79a-4ac7-ba29-a9935643b20f@d4g2000prg.googlegroups.com> Hi everyone. I'm fairly new to Python, and even more new to socket programming. I think I've wrapped my head around sockets, and with that I want to create a Telnet-based chat server, the idea being people connect to the telnet servers with their clients and they all communicate. I've got the code working, but the server sends each letter to the clients on a new line! I've read about this kind of thing on Windows on Google, but I can't find a solution to this issue. I got the code from here - http://www.scribd.com/doc/134861/Sockets-Programming-with-python. When I get this working I want to take my knowledge of sockets and expand the code further. Here's the code: import socket import select class ChatServer: def __init__( self, port ): self.port = port; self.srvsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.srvsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.srvsock.bind(("", port)) self.srvsock.listen( 5 ) self.descriptors = [self.srvsock] print "ChatServer started, listening on port %s" % port def run( self ): while 1: (sread, swrite, sexc) = select.select( self.descriptors, [], [] ) for sock in sread: if sock == self.srvsock: self.accept_new_connection() else: data = '' string = sock.recv(100) if string == '': host,port = sock.getpeername() string = 'Client left %s:%s\r\n' % (host, port) self.broadcast_string( string, sock ) sock.close self.descriptors.remove(sock) else: host, port = sock.getpeername() newstring = '[%s:%s] %s\r\n' % (host, port, string) self.broadcast_string( newstring, sock ) def accept_new_connection( self ): newsock, (remhost, remport) = self.srvsock.accept() self.descriptors.append( newsock ) newsock.send("You're connected to the chat server!\r\n") string = 'Client joined %s:%s\r\n' % (remhost, remport) self.broadcast_string( string, newsock) def broadcast_string( self, string, omit_sock ): for sock in self.descriptors: if sock != self.srvsock and sock != omit_sock: sock.send(string) print string server = ChatServer( 2626 ).run() Can anyone help me find a solution to this? Any help would be appreciated. Thanks! From Robert.Bossy at jouy.inra.fr Fri Feb 29 11:55:06 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Fri, 29 Feb 2008 17:55:06 +0100 Subject: Problem round-tripping with xml.dom.minidom pretty-printer In-Reply-To: <413ae7f9-ee26-47c6-b269-3a356576db8d@d62g2000hsf.googlegroups.com> References: <413ae7f9-ee26-47c6-b269-3a356576db8d@d62g2000hsf.googlegroups.com> Message-ID: <47C838EA.1090502@jouy.inra.fr> Ben Butler-Cole wrote: > Hello > > I have run into a problem using minidom. I have an HTML file that I > want to make occasional, automated changes to (adding new links). My > strategy is to parse it with minidom, add a node, pretty print it and > write it back to disk. > > However I find that every time I do a round trip minidom's pretty > printer puts extra blank lines around every element, so my file grows > without limit. I have found that normalizing the document doesn't make > any difference. Obviously I can fix the problem by doing without the > pretty-printing, but I don't really like producing non-human readable > HTML. > > Here is some code that shows the behaviour: > > import xml.dom.minidom as dom > def p(t): > d = dom.parseString(t) > d.normalize() > t2 = d.toprettyxml() > print t2 > p(t2) > p('') > > Does anyone know how to fix this behaviour? If not, can anyone > recommend an alternative XML tool for simple tasks like this? Hi, The last line of p() calls itself: it is an unconditional recursive call so, no matter what it does, it will never stop. And since p() also prints something, calling it will print endlessly. By removing this line, you get something like: That seems sensible, imo. Was that what you wanted? An additional thing to keep in mind is that toprettyxml does not print an XML identical to the original DOM tree: it adds newlines and tabs. When parsed again these blank characters are inserted in the DOM tree as character nodes. If you toprettyxml an XML document twice in a row, then the second one will also add newlines and tabs around the newlines and tabs added by the first. Since you call toprettyxml an infinite number of times, it is expected that lots of blank characters appear. Finally, normalize() is supposed to merge consecutive sibling character nodes, however it will never remove character contents even if they are blank. That means that several character nodes will be replaced by a single one whose content is the concatenation of the respective content of the original nodes. Clear enough? Cheers, RB From jr9445 at ATT.COM Mon Feb 11 11:24:14 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Mon, 11 Feb 2008 10:24:14 -0600 Subject: CSV Reader In-Reply-To: <4b1e691a-53ff-4cee-8e15-5bf17f2b56ef@i12g2000prf.googlegroups.com> References: <43a3a0d8-9425-4bc5-90d3-894fe980d3f7@s19g2000prg.googlegroups.com> <4b1e691a-53ff-4cee-8e15-5bf17f2b56ef@i12g2000prf.googlegroups.com> Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of Mike P > Sent: Monday, February 11, 2008 11:10 AM > To: python-list at python.org > Subject: Re: CSV Reader > > Hi Larry, > > i'm still getting to grips with python, but rest assured i thinkn it's > better for me to write hte code for learnign purposes > > My basic file is here, it comes up with a syntax error on the > startswith line, is this because it is potentially a list? > My idea was to get the lines number where i can see Transaction ID and > then write out everything from this point into a new datafile. > > >From the docs for reader: "All data read are returned as strings. No automatic data type conversion is performed." Just use print or repr() to see what the row data looks. Then the method to check for 'transaction id' should be abundantly clear. for data in reader: print data print repr(data) > Would a better solution be just to use readlines and search for the > string with a counter and then write out a file from there? Yes you could, but the danger is that you get an insanely large file that blows out your memory or causes the process to swap to disk space (disk is slooooooooow.) Just loop through the lines and use a boolean flag to determine when to start printing. ***** The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA621 From hniksic at xemacs.org Fri Feb 15 06:41:33 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 15 Feb 2008 12:41:33 +0100 Subject: Assignment saves time? References: Message-ID: <87bq6iphua.fsf@mulj.homelinux.net> rpglover64 at gmail.com writes: > I tested this using the timeit module, and though the difference was > small, I would have expected the first code block to do slightly > worse, Can you post your entire benchmark, so that we can repeat it? When I tried the obvious, I got the expected result: $ python -m timeit -s 'l=[]' 'len(l)==1000' 1000000 loops, best of 3: 0.256 usec per loop $ python -m timeit -s 'l=[]' 'len(l)==1000' 1000000 loops, best of 3: 0.27 usec per loop $ python -m timeit -s 'l=[]' 's=len(l); s==1000' 1000000 loops, best of 3: 0.287 usec per loop $ python -m timeit -s 'l=[]' 's=len(l); s==1000' 1000000 loops, best of 3: 0.299 usec per loop From groups.diegopark at gmail.com Mon Feb 4 08:00:24 2008 From: groups.diegopark at gmail.com (groups.diegopark at gmail.com) Date: Mon, 4 Feb 2008 05:00:24 -0800 (PST) Subject: PyOpenGL Message-ID: Hi all, I apologize if this question was already answered before but I was unable to find a proper solution to my problem. Anyways, I am trying to run shaderobjects.py on Windows (Python 2.5.1) by just double- clicking, and I got the following error: [...] File "/usr/lib/python2.5/site-packages/OpenGL/extensions.py", line 13, in hasGLExtension AVAILABLE_GL_EXTENSIONS[:] = glGetString( GL_EXTENSIONS ).split() AttributeError: 'NoneType' object has no attribute 'split' _I think_ I have all requirements and packages properly installed. Any clues? Thanks in advance ! Regards, Diego Park From castironpi at gmail.com Tue Feb 12 12:20:32 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 12 Feb 2008 09:20:32 -0800 (PST) Subject: call 'the following function' using decorators Message-ID: <4881cc78-85cc-4cf4-8e70-8089374d08f9@v17g2000hsa.googlegroups.com> I assert it's easier to write: start_new_thread( this_func ) def thrA(): normal_suite() than def thrA(): normal_suite() start_new_thread( thrA ) If you don't, stop reading. If you do, accomplish it like this: @decwrap( start_new_thread, Link, ( 2, 3 ) ) def anonfunc( a, b ): print( a, b ) where 'Link' replaces the following func, plus in keywords too: @decwrap( Thread, None, target= Link, args= ( 2, 3 ) ) def sampleth( a, b ): print( a, b ) sampleth.start() sampleth.join() 'Link' is a pseudo-constant. Link= object() @decwrap follows. def decwrap( func, *ar, **kwar ): def predec( func2 ): ar2= list( ar ) while Link in ar2: ar2[ ar2.index( Link ) ]= func2 kwar2= kwar.copy() for k, v in kwar2.items(): if v is not Link: continue kwar2[ k ]= func2 ret= func( *ar2, **kwar2 ) return ret return predec Further applications: @decwrap( button.bind, "", Link ) def anonfunc(): print( 'Key X pressed' ) Optional stylism for readability: @decwrap( start_new_thread, ~Link, ( 2, 3 ) ) @decwrap( Thread, None, target= ~Link, args= ( 2, 3 ) ) @decwrap( button.bind, "", ~Link ) where 'Link' is: class NegMarking: def __invert__( self ): return self Link= NegMarking() From wolf_tracks at invalid.com Fri Feb 15 10:55:26 2008 From: wolf_tracks at invalid.com (W. Watson) Date: Fri, 15 Feb 2008 07:55:26 -0800 Subject: Pop-up Menu of a Graphics Image? Message-ID: Is there a library that contains a pop-up menu class from a mouse click on a graphics image? -- Wayne Watson (Nevada City, CA) Web Page: From castironpi at gmail.com Tue Feb 12 13:58:36 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 12 Feb 2008 10:58:36 -0800 (PST) Subject: C function in a Python context References: <4717e82c-0b92-4e05-8ab9-4c2e8fc2ad3f@s12g2000prg.googlegroups.com> Message-ID: <272080e3-2073-435a-9625-bb2ce6feb68b@s13g2000prd.googlegroups.com> On Feb 9, 3:04?pm, castiro... at gmail.com wrote: > On Feb 9, 1:48?pm, castiro... at gmail.com wrote: > > > > > > > To write quick C things that Python won't do up to speed. ?So it's got > > a redundancy. > > > import ext > > extA= ext.Ext() > > extA[ 'enumfactors' ]= r""" > > ? ? int enumfactors( int a, const char* sep ) { > > ? ? ? ? int ret= 0, i; > > ? ? ? ? for( i= 1; i<= a; i++ ) { > > ? ? ? ? ? ? if( a% i== 0 ) { > > ? ? ? ? ? ? ? ? ret+= 1; > > ? ? ? ? ? ? ? ? if( i> 1 ) { > > ? ? ? ? ? ? ? ? ? ? printf( "%s", sep ); > > ? ? ? ? ? ? ? ? } > > ? ? ? ? ? ? ? ? printf( "%i", i ); > > ? ? ? ? ? ? } > > ? ? ? ? } > > ? ? ? ? printf( "\n" ); > > ? ? ? ? return ret; > > ? ? } > > ? ? """, ("i","i","s") > > > factorsn= extA.enumfactors( 209677683, ', ' ) > > print( "%i factors total."% factorsn ) > > > import sys > > sys.exit() > > > 1, 3, 23, 69, 131, 393, 3013, 9039, 23197, 69591, 533531, 1600593, > > 3038807, 9116 > > 421, 69892561, 209677683 > > 16 factors total. > > '''Prototype implementation, slightly rigid. ?If anyone knows how to > compile and link without intermediate object file, and from a string, > memory, or stdin, let me know. ?Change first four lines. ?If you are > not using gcc, look at regenpyd().''' > > compilercommand= ? ?'c:/programs/mingw/bin/gcc' > pythondll= ? ? ? ? ?'python30' > pythonpathinclude= ?'c:/programs/python/include' > pythonpathlibs= ? ? 'c:/programs/python/libs' > > class Ext: > ? ? strctypes= { 'i': 'int', 's': 'const char*' } > ? ? class ExtElem: > ? ? ? ? def __init__( self, name, code, types ): > ? ? ? ? ? ? self.name, self.code= name, code > ? ? ? ? ? ? self.types= types > ? ? def __init__( self ): > ? ? ? ? self.__dict__[ 'exts' ]= [] > ? ? def regenc( self ): > ? ? ? ? extcode= open( 'extcode.c', 'w' ) > ? ? ? ? wr= extcode.write > ? ? ? ? wr( '#include <%s'% pythonpathinclude ) > ? ? ? ? wr( '/Python.h>\n\n' ) > ? ? ? ? for ext in self.exts: > ? ? ? ? ? ? wr( ext.code ) > ? ? ? ? ? ? wr( '\n' ) > ? ? ? ? for ext in self.exts: > ? ? ? ? ? ? wr( 'static PyObject *\n' ) > ? ? ? ? ? ? wr( 'extcode_%s'% ext.name ) > ? ? ? ? ? ? wr( '(PyObject *self, ' ) > ? ? ? ? ? ? wr( 'PyObject *args) {\n' ) > ? ? ? ? ? ? wr( '\t%s result;\n'% > ? ? ? ? ? ? ? ? Ext.strctypes[ext.types[0]] ) > ? ? ? ? ? ? for i, type in enumerate( ext.types[1:] ): > ? ? ? ? ? ? ? ? wr( '\t%s arg%i;\n'% > ? ? ? ? ? ? ? ? ? ? ( Ext.strctypes[type], i ) ) > ? ? ? ? ? ? wr( '\tPyArg_ParseTuple(args, "' ) > ? ? ? ? ? ? wr( ''.join( ext.types[1:] ) ) > ? ? ? ? ? ? wr( '"' ) > ? ? ? ? ? ? for i, type in enumerate( ext.types[1:] ): > ? ? ? ? ? ? ? ? wr( ', &arg%i'% i ) > ? ? ? ? ? ? wr( ' );\n' ) > ? ? ? ? ? ? wr( '\tresult= %s( '% ext.name ) > ? ? ? ? ? ? wr( ', '.join( [ 'arg%i'% i for i > ? ? ? ? ? ? ? ? in range( len( ext.types[1:] ) ) ] ) ) > ? ? ? ? ? ? wr( ' );\n' ) > ? ? ? ? ? ? wr( '\treturn Py_BuildValue' ) > ? ? ? ? ? ? wr( '( "%s", result );\n'% ext.types[0] ) > ? ? ? ? ? ? wr( '}\n\n' ) > ? ? ? ? wr( 'static PyMethodDef ExtcodeMethods[] = {\n' ) > ? ? ? ? for ext in self.exts: > ? ? ? ? ? ? wr( '\t{ "%s", extcode_%s, '% > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ( ext.name, ext.name ) ) > ? ? ? ? ? ? wr( 'METH_VARARGS, "" },\n' ) > ? ? ? ? wr( '\t{NULL, NULL, 0, NULL}\n' ) > ? ? ? ? wr( '};\n\n' ) > ? ? ? ? wr( 'PyMODINIT_FUNC\n' ) > ? ? ? ? wr( 'initextcode(void) {\n' ) > ? ? ? ? wr( '\t(void) Py_InitModule' ) > ? ? ? ? wr( '("extcode", ExtcodeMethods);\n' ) > ? ? ? ? wr( '}\n\n' ) > ? ? ? ? extcode.close() > ? ? def regenpyd( self ): > ? ? ? ? import os, os.path > ? ? ? ? if os.path.exists( 'extcode.pyd' ): > ? ? ? ? ? ? os.remove( 'extcode.pyd' ) > ? ? ? ? import subprocess > ? ? ? ? retcompile= subprocess.call( > ? ? ? ? ? ? '%s extcode.c -c -I%s'% > ? ? ? ? ? ? ( compilercommand, pythonpathinclude ) ) > ? ? ? ? assert not retcompile, 'Compiler error' > ? ? ? ? retlink= subprocess.call( > ? ? ? ? ? ? '%s -shared extcode.o -o extcode.pyd -L%s -l%s' > ? ? ? ? ? ? % ( compilercommand, pythonpathlibs, > ? ? ? ? ? ? pythondll ) ) > ? ? ? ? assert not retlink, 'Linker error' > ? ? ? ? os.remove( 'extcode.o' ) > ? ? ? ? os.remove( 'extcode.c' ) > ? ? def __setitem__( self, key, value ): > ? ? ? ? code, types= value > ? ? ? ? self.exts.append( Ext.ExtElem( key, code, types ) ) > ? ? ? ? self.regenc() > ? ? ? ? self.regenpyd() > ? ? ? ? import extcode > ? ? ? ? setattr( self, key, getattr( extcode, key ) )- Hide quoted text - > > - Show quoted text - This is- and returns a list, of the enumerated factors. Is it starting to get bulky. import ext extA= ext.Ext() extA[ 'enumfactors' ]= r""" #include #include using namespace std; PyObject* enumfactors( int a, const char* sep ) { string fmt= "["; vector< long > resv; for( int i= 1; i<= a; i++ ) { if( a% i== 0 ) { resv.push_back( i ); fmt.append( "i" ); if( i> 1 ) { printf( "%s", sep ); } printf( "%i", i ); } } printf( "\n" ); fmt.append( "]" ); PyObject* res= PyList_New( resv.size() ); for( int i= 0; i< resv.size(); i++ ) { PyObject* v= PyLong_FromLong( resv[i] ); int succ= PyList_SetItem( res, i, v ); } return res; } """, ("O","i","s") factorsn= extA.enumfactors( 209677683, ', ' ) print( factorsn ) From emailamit at gmail.com Wed Feb 6 17:37:59 2008 From: emailamit at gmail.com (Amit Gupta) Date: Wed, 6 Feb 2008 14:37:59 -0800 (PST) Subject: getting all user defined attributes of a class References: <305a63f1-70b0-4234-ac6f-4fa1a43b5c78@e10g2000prf.googlegroups.com> <60upr7F1sat47U1@mid.uni-berlin.de> Message-ID: <5489736a-dc8e-47f3-8d5e-4a7d24dc37bd@j20g2000hsi.googlegroups.com> On Feb 6, 2:15 pm, Marc 'BlackJack' Rintsch wrote: > On Wed, 06 Feb 2008 14:07:23 -0800, Amit Gupta wrote: > > Class A(object) : > > self.x = 1 > > This is not valid Python code. > > > I want something like: > > for userattrib in A.getAllUserAttribute() : > > print userattrib > > > My question is, is there a builtin function, called > > getAllUserAttributes? > > No and there can't be since the attributes you seem to be interested in > don't exist until an instance is created. > > Ciao, > Marc 'BlackJack' Rintsch My mistake: I should make class A as: class A (object) : x = 1 Now, x is class attribute and I am looking for some-way to filter non- user-defined attributes. e.g.g if I do for attr in a.__dict__ : print attr I will also get __module__, __weakref__ and others including "x" Thanks From shore.cloud at gmail.com Sun Feb 24 10:19:28 2008 From: shore.cloud at gmail.com (Mr Shore) Date: Sun, 24 Feb 2008 07:19:28 -0800 (PST) Subject: mapping problem References: <04886f27-d234-4aa9-8ca4-5e720bf88a54@s19g2000prg.googlegroups.com> <13rdf3fggdreb91@corp.supernews.com> Message-ID: <4f5d26f9-d7b5-4d53-8e0d-cea9ae47e362@p73g2000hsd.googlegroups.com> yes you guessed perfectly I'm not a native English speaker sorry for my poor english.. On Feb 16, 6:35?pm, Steven D'Aprano wrote: > On Sat, 16 Feb 2008 01:35:32 -0800,MrShorewrote: > > I've now crawled the meta infor,but with multi name all means the same > > thing, > > such as MS,microsoft,microsoft corporation all means the same thing, how > > can I mapping words like this to the same thing? > > The same way you would map anything: use a dict. > > You know, sometimes I'm astounded by the ability of the human brain to > find semantic meaning in what is grammatically and syntactically > gibberish. Most of the words are English, but putting them all together > makes no sense. And yet, by interpolating between key words, I can guess > that the poster wants something like this: > > mapping = {"MS": "Microsoft", "Microsoft": "Microsoft", > "Microsoft Corporation": "Microsoft"} > > If I have guessed poorly, could you please try again, more carefully? If > you're not a native English speaker, please say so and we'll make > allowances, and if you are a native English speaker with no cognitive > disabilities, you should be ashamed of wasting our time with such poor > communication. > > -- > Steven > who is unapologetic for being grumpy about the oxygen-thieves using the > Internet these days, and if that makes me a curmudgeon, so be it. From jr9445 at ATT.COM Wed Feb 6 10:04:51 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Wed, 6 Feb 2008 09:04:51 -0600 Subject: Why not a Python compiler? In-Reply-To: <7da40f42-f64f-4939-a0dc-d24d1ff85f2d@v4g2000hsf.googlegroups.com> References: <28eead2f-a40c-414b-bd3d-a941f8a851a2@d70g2000hsb.googlegroups.com> <7da40f42-f64f-4939-a0dc-d24d1ff85f2d@v4g2000hsf.googlegroups.com> Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of Luis M. Gonz?lez > Sent: Tuesday, February 05, 2008 6:44 PM > To: python-list at python.org > Subject: Re: Why not a Python compiler? > > > Pypy is a very ambitious project and it aims, amongst many other > goals, to provide a fast just-in-time python implementation. > They even say that the "secret goal is being faster than c, which is > nonsense, isn?t it?" (I still didn?t get the joke though...). > 'c' is also the speed of light. And since nothing can travel faster than light... One demerit has been marked against your geek card for missing an obvious science pun. Additionally, your membership to the Star Trek Lifestyle Adventure Club has been put on probationary status for the next twelve parsecs. ***** The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA621 From stefan_ml at behnel.de Fri Feb 1 01:00:54 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 01 Feb 2008 07:00:54 +0100 Subject: REALLY simple xml reader In-Reply-To: References: <1090e4100801271040n7bc6b452n346adee02abcd91d@mail.gmail.com> <60do34F1q1qmlU1@mid.uni-berlin.de> <60dsbrF1qj28sU1@mid.uni-berlin.de> <87tzkujeq6.fsf@benfinney.id.au> <13q3ri2707niqc6@corp.supernews.com> <87odb1k9ar.fsf@benfinney.id.au> Message-ID: <47a2b596$0$27209$9b4e6d93@newsspool1.arcor-online.net> Ivan Illarionov wrote: >> Also, for XML documents, they were probably thinking that the >> documents will be machine-generated most of the time. As far as I can >> tell, they were right in that. > > If anybody has to deal with human-generated XML/HTML in Python it may > be better to use something like http://www.crummy.com/software/BeautifulSoup/ > > Bad XML markup is part of our life and there are great tools for this > use-case too. The good thing about 'bad XML' is that it's not XML, which is easy to tell. Stefan From castironpi at gmail.com Fri Feb 29 16:26:32 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 29 Feb 2008 13:26:32 -0800 (PST) Subject: How to subclass a built-in int type and prevent comparisons References: <21CFA1FC32D3214EBFA2F449FF211E310EAD2948@nypcmg1exms318.leh.lbcorp.lehman.com> Message-ID: <22f99d39-01ba-45e7-93c2-15755eedd1c7@x41g2000hsb.googlegroups.com> On Feb 29, 3:09?pm, "Terry Reedy" wrote: > "Bronner, Gregory" wrote in message > > news:21CFA1FC32D3214EBFA2F449FF211E310EAD2948 at nypcmg1exms318.leh.lbcorp.lehman.com... > | The native implementation of int goes to great lengths to allow > | illogical comparisons such as the one below. > | >>> import xml as x > | >>> x > | >>> > | > | >>> x>4 > | True > | >>> x<4 > | False > > Python once made all objects comparable. > No longer true. > 'Illogical' comparisons will raise exceptions in 3.0 > but must be maintained in 2.x for back compatibility. > > tjr Tell Wall. But why not [ 2, 3 ]>= 2? Back to your question, another option is to not subclass. From luismgz at gmail.com Wed Feb 13 13:58:34 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M._Gonz=E1lez?=) Date: Wed, 13 Feb 2008 10:58:34 -0800 (PST) Subject: Is there a way to use .NET DLL from Python References: <85706ba0-8c24-4324-9a79-98c97fc802db@e4g2000hsg.googlegroups.com> <6c2845aa-aec5-4b75-852a-551b9cd1d6ab@f10g2000hsf.googlegroups.com> <5845a12f-41dd-4bb3-8684-483e93f55c5f@e25g2000prg.googlegroups.com> <5cbdc3cf-cb84-49e5-b746-2eca0feeb97d@i7g2000prf.googlegroups.com>, <2298129a-3ca5-41f9-86ed-28805397fd54@f47g2000hsd.googlegroups.com> Message-ID: <2a883225-7622-4dc4-be85-daf4ff3cfe6c@u10g2000prn.googlegroups.com> On 13 feb, 00:26, Dino Viehland wrote: > >> Oh, I know what you mean. > >> But that was exactly the reason for having a .DLLs folder, isn't it? > >> When you place an assembly into this folder, you avoid having to write > >> this boilerplate code, and simply import the assembly as you would > >> with a normal python module. At least, that?s how it worked in > >> previous versions... > >No. You have always had to add references to assemblies before being > >able to use the namespaces they contain. You even have to do this with > >C# in Visual Studio. > > This *should* work in both IronPython 1.x and IronPyton 2.0 - the catch though is that it's implemented in the default site.py we ship with. So if you do the usual thing and use CPython's Lib directory you'll lose this feature w/o copying it over. Sorry Dino, I don't understand... What does Cpython's Lib have to do with it? From sjmachin at lexicon.net Thu Feb 14 06:29:24 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 14 Feb 2008 03:29:24 -0800 (PST) Subject: Looking for a Python Program/Tool That Will Add Line Numbers to a txt File References: <4BRsj.10199$Ch6.5665@newssvr11.news.prodigy.net> Message-ID: <446814ba-184e-44ad-bda9-05c1817af950@72g2000hsu.googlegroups.com> On Feb 14, 6:13 pm, Chris wrote: > On Feb 14, 8:54 am, "W. Watson" wrote: > > > See Subject. It's a simple txt file, each line is a Python stmt, but I need > > up to four digits added to each line with a space between the number field > > and the text. Perhaps someone has already done this or there's a source on > > the web for it. I'm not yet into files with Python. A sudden need has burst > > upon me. I'm using Win XP. > > -- > > Wayne Watson (Nevada City, CA) > > > Web Page: > > enumerate through the file which will yield you a counter (starting @ > zero so just add 1) and use the string function .zfill() to pad it out > for you. > eg. > > for (line_cnt, each_line) in enumerate(input_file): > output_file.write(print ('%s '%(line_cnt+1)).zfill(5) + each_line) (1) What's that "print" doing in there? (2) zfill(5)? The OP asked for "up to 4 digits", not 5. (2) As an alternative to str.zfill, consider using formatting: output_file.write('%04d %s' % (line_cnt+1, each_line)) And what does "up to 4" mean? What does the OP want the 10000th line to look like? From http Fri Feb 22 13:54:15 2008 From: http (Paul Rubin) Date: 22 Feb 2008 10:54:15 -0800 Subject: Simple - looking for a way to do an element exists check.. References: <7x8x1c25cz.fsf@ruckus.brouhaha.com> Message-ID: <7x3ark2560.fsf@ruckus.brouhaha.com> Paul Rubin writes: > if any(x==element[0] for x in a): > a.append(element) Should say: if any(x[0]==element[0] for x in a): a.append(element) From MartinRinehart at gmail.com Wed Feb 20 07:17:04 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Wed, 20 Feb 2008 04:17:04 -0800 (PST) Subject: Python Memory Manager References: <0c69faf6-c019-425b-b988-fc2b76befd3d@60g2000hsy.googlegroups.com> <7xejbb6zss.fsf@ruckus.brouhaha.com> <7885d6a5-0aa0-4ef5-b409-a954170ae9da@i7g2000prf.googlegroups.com> Message-ID: <35791c4b-2cbc-4fa5-b50b-944f5178febe@28g2000hsw.googlegroups.com> Steve Holden wrote: > You have a strange idea of "nearly free" ... > > Extending an integer array from 100 to 150 items is a pretty puny > operation when you compare it with the amount of data that might need to > be moved during a compactifying garbage collection of a 20MB Python > program image. 20 MBs = 5 M 32-bit words = 1.25 millis to move half of them on a 2GHz machine. Don't know how much a milli costs where you live. From arnodel at googlemail.com Tue Feb 5 16:56:03 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 5 Feb 2008 13:56:03 -0800 (PST) Subject: IronPython vs CPython: faster in 1.6 times? References: <52c34392-5c5b-49b8-8c75-ba9add438b73@k39g2000hsf.googlegroups.com> Message-ID: <2995994a-487c-4797-ad01-0989cd9ea40a@l16g2000hsh.googlegroups.com> On Feb 5, 8:01?pm, Istvan Albert wrote: > On Feb 5, 12:31 pm, dmitrey wrote: > > > Hi all, > > the urlhttp://torquedev.blogspot.com/2008/02/changes-in-air.html > > (blog of a game developers) > > says IronPython is faster than CPython in 1.6 times. > > Is it really true? > > This is a second time around that IronPython piqued my interest > sufficiently to create a toy program to benchmark it and I must say > the results are not encouraging: > > $ python bench.py > Elapsed time: 1.10 s > > $ ipy bench.py > Elapsed time:65.01 s > > and here is the benchmark program: > > import time > start = time.time() > > def foo(a): > ? ? return a * a > > data = {} > for i in xrange( 10**6 ): > ? ? data[i] = foo(i) > > print 'Elapsed time:%5.2f s' % ( time.time() - start) Could it be because .NET doesn't have arbitrary length integer types and your little benchmark will create lots of integers > 2**32 ? What is the result if you replace foo(a) with def foo(a): return sqrt(a) -- Arnaud From george.sakkis at gmail.com Tue Feb 12 23:36:02 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 12 Feb 2008 20:36:02 -0800 (PST) Subject: ways to declare empty set variable References: <56a14$47b1a306$839b8704$9583@news2.tudelft.nl> <5099c$47b1a77b$839b8704$11089@news2.tudelft.nl> <7xhcgd7tof.fsf@ruckus.brouhaha.com> <719e7c26-7d52-4b78-875c-fc7d5ca32f4e@s19g2000prg.googlegroups.com> <874pcdzsho.fsf@benfinney.id.au> <87zlu5yb9h.fsf@benfinney.id.au> <6dd61cff-f27e-42e7-9802-7220e063fa07@y5g2000hsf.googlegroups.com> <87fxvxy4dt.fsf@benfinney.id.au> Message-ID: <44440daa-aa28-4bbc-af09-42148c90e405@d70g2000hsb.googlegroups.com> On Feb 12, 9:30 pm, Ben Finney wrote: > George Sakkis writes: > > On Feb 12, 7:02 pm, Ben Finney > > wrote: > > > That makes it even more a violation of > > > principle-of-least-astonishment that the '(foo)' form doesn't give > > > a one-element tuple literal. > > > The reason being, of course, that in this case '(1+2) * 3' would > > give a result several orders of magnitude more astonishing, > > Yes, of course. > > > so it's well worth the slight inconvenience of one-element tuples. > > I didn't make it clear, but my expected solution to this is that '()' > should not create an empty tuple (as I was clearly assuming earlier in > this thread). An empty set can still be created with 'set()'. > > That way, it becomes clearer that it's the comma separator, not the > parens, that create a tuple literal. With '()' creating an empty tuple > literal, and '(foo, bar)' creating a two-element tuple literal, it > remains that much harder to remember that '(foo)' does *not* create a > tuple. *shrug* I've never been bitten by this. From a purist POV I see your point but I guess it's one of the things you learn when you first pick up Python and never have to think again. George From bbxx789_05ss at yahoo.com Wed Feb 20 19:56:47 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Wed, 20 Feb 2008 16:56:47 -0800 (PST) Subject: Querying a complex website References: <2862c627-7a7c-4b17-adef-2fddfd027791@d21g2000prf.googlegroups.com> <10917c84-c8f7-42cb-9248-b0d7a6019985@u10g2000prn.googlegroups.com> Message-ID: <4bc3d6e9-bab3-4086-a9f3-3559f6b973e4@n77g2000hse.googlegroups.com> schweet1 wrote: > On Feb 19, 4:04?pm, 7stud wrote: > > schweet1 wrote: > > > Greetings, > > > > > I am attempting to use python to submit a query to the following URL: > > > > >https://ramps.uspto.gov/eram/patentMaintFees.do > > > > > The page looks simple enough - it requires submitting a number into 2 > > > form boxes and then selecting from the pull down. > > > > > However, my test scripts have been hung up, apparently due to the > > > several buttons on the page having the same name. ?Ideally, I would > > > have the script use the "Get Bibligraphic Data" link. > > > > > Any assistance would be appreciated. > > > > > ~Jon > > > > This is the section you are interested in: > > > > ------------- > > > > > value="Retrieve Fees to Pay"> > > > > > > > > > > > > > > > > > > > > > > ------------ > > > > 1) When you click on a submit button on a web page, a request is sent > > out for the web page listed in the action attribute of the
tag, > > which in this case is: > > > > > > > > The url specified in the action attribute is a relative url. ?The > > current url in the address bar of your browser window is: > > > > https://ramps.uspto.gov/eram/patentMaintFees.do > > > > and if you compare that to the url in the action attribute of the > > tag: > > > > ---------https://ramps.uspto.gov/eram/patentMaintFees.do > > > > /eram/getMaintFeesInfo.do;jsessionid=0000-MCoYNbJsaUCr2VfzZhKILX: > > 11g0uepfb > > --------- > > > > you can piece them together and get the absolute url: > > > > https://ramps.uspto.gov/eram/getMaintFeesInfo.do;jsessionid=0000-MCoY... > > > > 2) When you click on a submit button, a request is sent to that url. > > The request will contain all the information you entered into the form > > as name/value pairs. ?The name is whatever is specified in the name > > attribute of a tag and the value is whatever is entered into the form. > > > > Because the submit buttons in the form have name attributes, ?the name > > and value of the particular submit button that you click will be added > > to the request. > > > > 3) ?To programmatically mimic what happens in your browser when you > > click on the submit button of a form, you need to send a request > > directly to the url listed in the action attribute of the . > > Your request will contain the name/value pairs that would have been > > sent to the server if you had actually filled out the form and clicked > > on the 'Get Bibliographic Data' submit button. ?The form contains > > these input elements: > > > > ---- > > > > > > > value=""> > > ---- > > > > and the submit button you want to click on is this one: > > > > > > > > So the name value pairs you need to include in your request are: > > > > data = { > > ? ? 'patentNum':'1234567', > > ? ? 'applicationNum':'08123456', > > ? ? 'maintFeeAction':'Get Bibliographic Data' > > > > } > > > > Therefore, try something like this: > > > > import urllib > > > > data = { > > ? ? 'patentNum':'1234567', > > ? ? 'applicationNum':'08123456', > > ? ? 'maintFeeAction':'Get Bibliographic Data' > > > > } > > > > enc_data = urllib.urlencode(data) > > url = 'https://ramps.uspto.gov/eram/ > > getMaintFeesInfo.do;jsessionid=0000-MCoYNbJsaUCr2VfzZhKILX:11g0uepfb' > > > > f = urllib.urlopen(url, enc_data) > > > > print f.read() > > f.close() > > > > If that doesn't work, you may need to deal with cookies that the > > server requires in order to keep track of you as you navigate from > > page to page. ?In that case, please post a valid patent number and > > application number, so that I can do some further tests.- Hide quoted text - > > > > - Show quoted text - > > Thanks all - I think there are cookie issues - here's an example data > pair to play with: 6,725,879 (10/102,919). I'll post some of the code > i've tried asap. Ok. Here is what your form looks like without all the and tags: ------------- for Payment Window:
---------------- First notice that there is a tag needs to be included in your request. That requires that you add the following data to your request: 'maintFeeYear':'04' #...or whatever you want the value to be Also notice that there are 'hidden' form fields in the form. They look like this: A hidden form field is not visible on a web page, but just the same its name/value pair gets sent to the server when the user submits the form. As a result, you need to include the name/value pairs of the hidden form fields in your request. It so happens that one of the hidden form field's name is 'sessionId'. That id identifies you as you move from page to page. If you click on a link or a button on a page, a request is sent out for another page, and if the request does not contain that sesssionID, then the request is rejected. What that means is: you cannot submit a request directly for the page you want. First, you have to send out a request for the page with the form on it and then extract some information from it. What you need to do is: 1) Request the form page. 2) Extract the name/value pairs in the hidden form fields on the form page. BeautifulSoup is good for doing things like that. You need to add those name/value pairs to the dictionary containing the patent number and the application number. 3) The url in the action attribute of the form looks like this: action="/eram/ getMaintFeesInfo.do;jsessionid=0000U8dQaywwUaYMMuwsl8h4WsX:11g0uehq7 Note how there is a 'jsessionid' on the end. What that means is: the url in the action attribute changes every time you go to the the form page. As a consequence, you cannot know that url beforehand. Because the information you want is at the url listed in the action attribute, you have to extract that url from the form page as well. Once again, BeautifulSoup makes that easy to do. Once you have 1) all the data that is required, and 2) the proper url to send your request to, then you can send out your request. Here is an example: import urllib import BeautifulSoup as bs #get the form page: response1 = urllib.urlopen('https://ramps.uspto.gov/eram/ patentMaintFees.do') #extract the url from the action attribute: html_doc = bs.BeautifulSoup(response1.read()) form = html_doc.find('form', attrs={'name':'mfInputForm'}) action_attr_url = form['action'] next_page_url = 'https://ramps.uspto.gov' + action_attr_url #create a dictionary for the data: form_data = { 'patentNum':'6725879', 'applicationNum':'10102919', 'maintFeeYear': '04', # hidden_tags = form.findAll('input', type='hidden') for tag in hidden_tags: name = tag['name'] value = tag['value'] print name, value #if you want to see what's going on form_data[name] = value #add the data to our dictionary #format the data and send out the request: enc_data = urllib.urlencode(form_data) response2 = urllib.urlopen(next_page_url, enc_data) print response2.read() response2.close() From steve at REMOVE-THIS-cybersource.com.au Fri Feb 22 13:16:06 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 22 Feb 2008 18:16:06 -0000 Subject: Return value of an assignment statement? References: <6d945394-739e-4c47-ad71-faaab8f9d566@34g2000hsz.googlegroups.com> <5ffc7183-6e32-42d1-b9a1-a7514cd085c3@i7g2000prf.googlegroups.com> <13rtopedoulfc5b@corp.supernews.com> <80aa9840-f279-4280-8ea3-c14148fe4c5e@m23g2000hsc.googlegroups.com> Message-ID: <13ru4b6356mfra1@corp.supernews.com> On Fri, 22 Feb 2008 08:19:07 -0800, Carl Banks wrote: > (The perl example wasn't using an assignment operator.) Hmmm... I see. Obviously I didn't pretend to understand Perl well enough. (I assume you're ignoring the assignments $name = chop(\1) etc. Fair enough.) [...] > I can't help but to think that a lot of people's distaste for this > natural way to write certain logic is simply defensiveness about one > minor little thing that Python doesn't support (without workarounds). But Python certainly does support set-and-test. You just have to separate the set from the test with a newline: m = re.match(r"name=(.*)",line) # set if m: # test name = m.group(1).strip() This does the same thing as your proposed syntax if m where m = re.match(r"name=(.*)",line): name = m.group(1).strip() except that it doesn't create a new scope. I'm not sure that the benefit of having a new scope is worth the new keyword. Maybe it is, maybe it isn't. I think I have a better idea of what you are trying to say. Despite first impressions, you weren't defending the proposed "assign-and-test" idiom suggested by Stephen Gross: pat = re.compile('some pattern') if m = pat.match(some_string): # doesn't work in Python do_something(m) on account of it needing an assignment expression, which is Bad. But you were defending the principle of set-and-test, if we can use something other than an assignment expression to do the set. E.g. Perl's magic syntax "if /pattern/ { }" (everything in Perl is magic syntax), or your proposed "if m where m = expression". Okay, I can agree with that, particularly since Python already supports it using the plain old boring, old fashioned idiom of "assign, then test". -- Steven From furkankuru at gmail.com Thu Feb 7 18:05:46 2008 From: furkankuru at gmail.com (Furkan Kuru) Date: Fri, 8 Feb 2008 01:05:46 +0200 Subject: embedded python in c++ packaging In-Reply-To: References: <3a4a8f930802070839n31ac4d88t96d64a4138d23ff4@mail.gmail.com> Message-ID: <3a4a8f930802071505x70946723wabe84ad9ea4ae465@mail.gmail.com> I do not have access to my development machine right now. but is it enough adding just a simple line at the top of my main python file 'sys.path.append("modules.zip")' before importing any other modules? On 2/7/08, Gabriel Genellina wrote: > > En Thu, 07 Feb 2008 16:18:57 -0200, Joshua Kugler > escribi?: > > Furkan Kuru wrote: > >> > >> I have been developing an application in C++ that embeds Python > >> interpreter. It takes advantage of too many modules from Python. > >> When I want to package this application, I need to add too many files > >> (.pyc) from Python/lib folder together with Python25.dll. > >> Is there a way to pack these .pyc files to a zip file and redirect > >> Python25.dll to that zip file? > > > > That is effectively what py2exe does with the modules required by the > > main > > application. It takes all the required modules and puts them in a > > library.zip file. You might take a look at how it does it. > > Using py2exe has an additional advantage, it recursively scans all modules > looking for dependencies. > Once you know the required set of modules, you can bundle them in a .zip > file and add its full path into sys.path (the absolute path including > filename and .zip extension). Python does look into the .zip searching for > modules. > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Furkan Kuru -------------- next part -------------- An HTML attachment was scrubbed... URL: From dotancohen at gmail.com Wed Feb 20 05:37:04 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Wed, 20 Feb 2008 12:37:04 +0200 Subject: The big shots In-Reply-To: <823e82d6-4faf-453f-9330-a34c262c2f52@e25g2000prg.googlegroups.com> References: <89d15587-e8de-444c-b240-4a10305146e0@e23g2000prf.googlegroups.com> <7xmypx61z6.fsf@ruckus.brouhaha.com> <823e82d6-4faf-453f-9330-a34c262c2f52@e25g2000prg.googlegroups.com> Message-ID: <880dece00802200237w741649f3u7cb9d616f684b86c@mail.gmail.com> On 20/02/2008, castironpi at gmail.com wrote: > I'm going to start marking my subjective comments with a star, so it's > clear what is emperically verifiable, and what is not. An ascii star? You do realize that email is a text medium, no? > It's a bad sign. If you aren't keeping your thoughts to yourself, and > thrashing about the world for a peer, a social network, a support > group, or a community, then you missed the day in grammar school when > they were handing out smiles. But they're not handing them out > anymore. You talk in analogies. I don't understand them. I do not know Spanish, and maybe if I knew both Spanish and your local customs, I would understand your analogies. But as a Hebrew-speaking middle easterner, I don't. > Even on my emperical claims, I'm wrong 90% of the time. On the > subjective ones, I'm not only wrong that much, but no one else want to > hear, or even can verify them. Smell's fine to me. I don't have time for 10% right. I cannot go verify everything that you think out loud because 10% might be true. No matter how it smells to you. > Emotions are prejudiced; and even in my own concrete thoughts, I will > misidentify myself with another, and others with me. When I say "I", > I mean "you." I believe that text was reworded for the final draft of "Through the Looking Glass". > French and Spanish have impersonal pronouns: "on" and "se", > respectively. In English, they often come out as, "we", "they", and > "you" a lot, on occasion a "one", and sometimes, even, I. In Hebrew, we have 8 different words for "you". That does not affect my English communications, however. Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From dblubaugh at belcan.com Thu Feb 7 19:05:09 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Thu, 7 Feb 2008 19:05:09 -0500 Subject: Dear David (was: MyHDL project) In-Reply-To: <85624658-1ce7-4ce7-9109-3ac3500c7553@v4g2000hsf.googlegroups.com> References: <27CC3060AF71DA40A5DC85F7D5B70F38010E3792@AWMAIL04.belcan.com> <85624658-1ce7-4ce7-9109-3ac3500c7553@v4g2000hsf.googlegroups.com> Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F38024F7E12@AWMAIL04.belcan.com> I do not understand why people such as yourself cannot construct anything but insults and complaints. Please e-mail me something that is of reasonable technological value regarding Python development, not just informing me that that my messages are difficult to read under circumstances that are ridiculous at best. thanks. David -----Original Message----- From: ajaksu [mailto:ajaksu at gmail.com] Sent: Thursday, February 07, 2008 5:49 PM To: python-list at python.org Subject: Re: Dear David (was: MyHDL project) On Feb 7, 4:48 pm, "Blubaugh, David A." wrote: > sir, > > Is there still a possibility to collaborate??? > > David Blubaugh Dear David A. Blubaugh, Could you please make it a little less painful to read your messages? You're giving a bad name to Belcan, too. Daniel This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From http Mon Feb 11 15:24:21 2008 From: http (Paul Rubin) Date: 11 Feb 2008 12:24:21 -0800 Subject: Encrypting a short string? References: Message-ID: <7xy79rnswa.fsf@ruckus.brouhaha.com> erikcw writes: > database. I'm using this encrypted string to identify emails from a > user. (the string will be in the subject line of the email). 1. I hope you're not trying to spam anyone. 2. What happens if the user edits the subject line? > I'm trying to figure out which approach I should use to encrypt the > data. The string will be less than 20 characters long, and I'd like > the encrypted version to be about the same size. Under normal security requirements you cannot do this. The ciphertext has to be longer than the plaintext since you don't want the opponent to be able to tell whether two plaintexts are the same. Therefore you have to attach some random padding to each plaintext. Also, you presumably want the ciphertext to be encoded as printing characters, while normally you'd treat the input as binary, so there is some further expansion. From martin at v.loewis.de Mon Feb 11 00:56:58 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Mon, 11 Feb 2008 06:56:58 +0100 Subject: Displaying Unicode Chars In-Reply-To: References: <3c525772-85b1-49ff-a46b-48e7f03df6ca@v4g2000hsf.googlegroups.com> <47af6cec$0$27951$9b622d9e@news.freenet.de> Message-ID: <47afe3aa$0$23480$9b622d9e@news.freenet.de> > Thanks to both of you. Those approaches make sense. Here's the final > result if you're curious: http://utilitymill.com/utility/Display_Unicode_Char_From_Hex Not sure what operating system you are using. On Windows, I recommend that you look at the charmap.exe utility. On Linux, try gucharmap or kcharselect. Regards, Martin From info at thegrantinstitute.com Mon Feb 11 00:42:02 2008 From: info at thegrantinstitute.com (Anthony Jones) Date: 10 Feb 2008 21:42:02 -0800 Subject: Professional Grant Proposal Writing Workshop (May 2008: Denver, Colorado) Message-ID: <20080210214202.75789ACD7F47C08D@thegrantinstitute.com> An HTML attachment was scrubbed... URL: From cokofreedom at gmail.com Tue Feb 5 03:30:18 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Tue, 5 Feb 2008 00:30:18 -0800 (PST) Subject: Why not a Python compiler? References: <28eead2f-a40c-414b-bd3d-a941f8a851a2@d70g2000hsb.googlegroups.com> Message-ID: <81339c25-f9b6-47a1-941e-8ae39c35773c@e6g2000prf.googlegroups.com> On Feb 5, 9:19 am, Santiago Romero wrote: > ( Surely if this question has been asked for a zillion of times... ) > ( and sorry for my english! ) > > I'm impressed with python. I'm very happy with the language and I > find Python+Pygame a very powerful and productive way of writing 2D > games. I'm not, at this moment, worried about execution speed of the > small game I'm working on (it runs at full 60 fps even in an old AMD- > K6 450 Laptop computer), but I continue asking me the same question: > > Why not a Python COMPILER? > > It would be very nice to be able to output Linux, MAC or Windows > binaries of compiled (not bytecompiled) code. It would run faster, it > will be smaller in size (I think) and it will be easy to distribute to > people not having python installed. Yes, I know about py2exe, but I'm > not sure if that's the right aproach. > > So, what's wrong with compiling python? > > Maybe is not possible due to nature of the language? Is just a > decision? > > What do you think about this? I don't know the exact details but I think the issue is the dynamic nature of Python makes it impossible to correctly store the various types and changes into compiled code. Someone else will probably be able to provide a good reason as to why it isn't very feasible, nor a good idea. If you want to speed up your python look at Psyco. http://psyco.sourceforge.net/ From grante at visi.com Tue Feb 26 12:29:58 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 26 Feb 2008 17:29:58 -0000 Subject: How about adding rational fraction to Python? References: <97f30679-483d-4751-9a6e-0858b36eb426@d4g2000prg.googlegroups.com> <649ac8a9-ae09-4e9b-85c2-f37043af21fd@28g2000hsw.googlegroups.com> <0d1955fc-762c-44e1-a5d8-372c71458455@p25g2000hsf.googlegroups.com> <36204e6f-0d82-449b-8ca5-c819ace9a55a@p73g2000hsd.googlegroups.com> <9503b14b-7bd5-42b4-b3f7-673d0ebd7feb@c33g2000hsd.googlegroups.com> <602ac27c-4aaa-49b2-bee2-1e0e0c705983@i7g2000prf.googlegroups.com> <1204034122.3318.3.camel@aalcdl07.lib.unc.edu> <20080226092955.cb13d595.darcy@druid.net> Message-ID: <13s8j4m1mqv9rc4@corp.supernews.com> On 2008-02-26, Steve Holden wrote: > D'Arcy J.M. Cain wrote: >> On Tue, 26 Feb 2008 08:55:22 -0500 >> "J. Cliff Dyer" wrote: >>> Of course. That's why I think you ought to spell it 3//4. Nobody gets >>> confused when a strange operator that they've never seen before does >>> something unusual. Average Jo off the street looks at python code and >>> sees 3/4, and immediately thinks "aha! .75!" Show the same person 3//4, >> >> Why do we care what A. Jo thinks? I would hope that A. Programmer Jo >> would see "int {OP} int" and assume int result. A. Jo isn't going to be >> debugging anything. >> >> If 3/4 ever returned 0.75 in any language I would drop that language. >> > Prepare to drop Python then, as this will be the default behavior in 3.x IIRC, That was the behavior in Pascal. If you wanted integer division you used the "div" operator. -- Grant Edwards grante Yow! I'm a nuclear at submarine under the visi.com polar ice cap and I need a Kleenex! From cfbolz at gmx.de Wed Feb 6 12:14:40 2008 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Wed, 06 Feb 2008 18:14:40 +0100 Subject: Why not a Python compiler? In-Reply-To: References: <28eead2f-a40c-414b-bd3d-a941f8a851a2@d70g2000hsb.googlegroups.com> <7da40f42-f64f-4939-a0dc-d24d1ff85f2d@v4g2000hsf.googlegroups.com> Message-ID: <47A9EB00.6000703@gmx.de> Reedick, Andrew wrote: >> -----Original Message----- >> From: python-list-bounces+jr9445=att.com at python.org [mailto:python- >> list-bounces+jr9445=att.com at python.org] On Behalf Of Luis M. Gonz?lez >> Sent: Tuesday, February 05, 2008 6:44 PM >> To: python-list at python.org >> Subject: Re: Why not a Python compiler? >> >> >> Pypy is a very ambitious project and it aims, amongst many other >> goals, to provide a fast just-in-time python implementation. >> They even say that the "secret goal is being faster than c, which is >> nonsense, isn?t it?" (I still didn?t get the joke though...). >> > > 'c' is also the speed of light. And since nothing can travel faster than light... nice theory, but wrong: The PyPy home page uses a capital letter C: http://codespeak.net/pypy/dist/pypy/doc/home.html Cheers, Carl Friedrich Bolz From bj_666 at gmx.net Tue Feb 26 09:41:50 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 26 Feb 2008 14:41:50 GMT Subject: How about adding rational fraction to Python? References: <97f30679-483d-4751-9a6e-0858b36eb426@d4g2000prg.googlegroups.com> <649ac8a9-ae09-4e9b-85c2-f37043af21fd@28g2000hsw.googlegroups.com> <0d1955fc-762c-44e1-a5d8-372c71458455@p25g2000hsf.googlegroups.com> <36204e6f-0d82-449b-8ca5-c819ace9a55a@p73g2000hsd.googlegroups.com> <9503b14b-7bd5-42b4-b3f7-673d0ebd7feb@c33g2000hsd.googlegroups.com> <602ac27c-4aaa-49b2-bee2-1e0e0c705983@i7g2000prf.googlegroups.com> <1204034122.3318.3.camel@aalcdl07.lib.unc.edu> Message-ID: <62impeF223i2qU5@mid.uni-berlin.de> On Tue, 26 Feb 2008 09:29:55 -0500, D'Arcy J.M. Cain wrote: > If 3/4 ever returned 0.75 in any language I would drop that language. Then prepare to drop Python from version 3 on: Python 3.0a1 (py3k, Aug 31 2007, 21:20:42) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 3 / 4 0.75 Ciao, Marc 'BlackJack' Rintsch From stefan_ml at behnel.de Fri Feb 1 12:26:50 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 01 Feb 2008 18:26:50 +0100 Subject: Pyrex bitten by the exception bug In-Reply-To: <47a333a9$0$85785$e4fe514c@news.xs4all.nl> References: <47a333a9$0$85785$e4fe514c@news.xs4all.nl> Message-ID: <47A3565A.9080109@behnel.de> Paul Sijben wrote: > I am running into the (apparently) well-known issue with pyrex that > trying to raise an exception using python2.5 and pyrex will lead to a > TypeError, as "TypeError: exceptions must be strings, classes, or > instances, not exceptions.ImportError" You should use a recent Pyrex version. But using Cython is a better idea anyway. Stefan From steve at holdenweb.com Fri Feb 1 11:30:02 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 01 Feb 2008 11:30:02 -0500 Subject: Will Python on day replace MATLAB? In-Reply-To: References: <27CC3060AF71DA40A5DC85F7D5B70F380239F7FC@AWMAIL04.belcan.com> <284a7$47a322a4$d4785a98$27655@cache6.tilbu1.nb.home.nl> Message-ID: Pete Forman wrote: > Jaap Spies writes: > > > Have a look at Sage: http://www.sagemath.org/ > > Of relevance to SciPy is the following > > http://wiki.sagemath.org/days8 > > | The Sage_ and Scipy_ teams and `Enthought Inc.`_ are pleased to > | announce the first collaborative meeting for Sage/Scipy joint > | development, to be held from February 29 until March 4, 2008 at the > | Enthought headquarters in Austin, Texas. > | > | The purpose of this meeting is to gather developers for these > | projects in a friendly atmosphere for a few days of technical talks > | and active development work. It should be clear to those > | interested in attending that this is *not* an academic conference, > | but instead an opportunity for the two teams to find common points > | for collaboration, joint work, better integration between the > | projects and future directions. The focus of the workshop will be > | to actually *implement* such ideas, not just to plan for them. Sorry, those question marks are hurting my eyeballs. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From bill.pursell at gmail.com Mon Feb 18 08:37:28 2008 From: bill.pursell at gmail.com (William Pursell) Date: Mon, 18 Feb 2008 05:37:28 -0800 (PST) Subject: Looking for a Python Program/Tool That Will Add Line Numbers to a txt File References: <4BRsj.10199$Ch6.5665@newssvr11.news.prodigy.net> Message-ID: On Feb 14, 6:54 am, "W. Watson" wrote: > See Subject. It's a simple txt file, each line is a Python stmt, but I need > up to four digits added to each line with a space between the number field > and the text. Perhaps someone has already done this or there's a source on > the web for it. I'm not yet into files with Python. A sudden need has burst > upon me. I'm using Win XP. Not sure if "Python program/tool" means "a tool or a program in Python", but if awk is okay, that's the tool I would use: awk '{printf( "%4d %s\n", NR % 10000, $0 )}' From james.pye at gmail.com Tue Feb 19 11:17:42 2008 From: james.pye at gmail.com (james.pye at gmail.com) Date: Tue, 19 Feb 2008 08:17:42 -0800 (PST) Subject: psycopg2: connect copy_from and copy_to References: <6209kgF20tdpgU1@mid.individual.net> Message-ID: > Doesn't PostGres come with Export/Import apps ? That would be easiest > (and faster). Yes, PostgreSQL core has import/export apps, but they tend to target general administration rather than transactional loading/moving of data. ie, dump and restore a database or schema. There is a pgfoundry project called pgloader that appears to be targeting a more general scenario of, well, loading data, but I imagine most people end up writing custom ETL for data flow. > Else, > > prod_cursor.execute('select data from production') > for each_record in cursor.fetchall(): > ? ? dev_cursor.execute('insert into testing') > > that is one way of doing it In any high volume cases you don't want to do that. The current best practice for loading data into an existing PostgreSQL database is create temp, load into temp using COPY, merge from temp into destination(the last part is actually the tricky one ;). From grante at visi.com Mon Feb 11 21:42:45 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 12 Feb 2008 02:42:45 -0000 Subject: OT: Star Wars and parsecs [was Re: Why not a Python compiler?] References: <28eead2f-a40c-414b-bd3d-a941f8a851a2@d70g2000hsb.googlegroups.com> <7da40f42-f64f-4939-a0dc-d24d1ff85f2d@v4g2000hsf.googlegroups.com> <13qjktdbe76da00@corp.supernews.com> <13qmp56btnr55a4@corp.supernews.com> <13qmtqebm4t6979@corp.supernews.com> <13qo0rkr7osv792@corp.supernews.com> <13qotf2mgpvkoac@corp.supernews.com> <9635c9ed-ba6e-4172-932f-01d88a625452@f10g2000hsf.googlegroups.com> Message-ID: <13r21t54i92npe6@corp.supernews.com> On 2008-02-10, mensanator at aol.com wrote: >>>> ? ? ? A Parsec is a fixed value (which, admittedly, presumes >>>> the culture developed a 360degree circle broken into degrees >>>> => minutes => seconds... or, at least, some units compatible >>>> with the concept of an "arc second", like 400 grads of, say, >>>> 100 "minutes", each of 100 "seconds") >> >>> It also presumes a standard diamter of that circle. >> >> Which is the Earth's orbit. ?So, long, long ago in a galaxy >> far, far away did they know about the Earth and decide to use >> it as the basis for length in the universe? ?Even before >> people on earth defined it? ? >> >> Or (ominous music builds here, switch to low voice) is it as >> some now contend? ?We are the decendents of a long, lost >> civilization who colonized Earth and used it as a base for >> their operations to the point of adopting it as their own >> home? >> >> ... ?You Betcha! >> >> :-) > > How come they spoke English? In some of the series, they sure didn't do it very well, but I presume they were forced to read what was written. If you want to see a movie where the aliens -- at least for part of the movie -- speak an alien language (with subtitles), there's "Battlefield Earth". It's amazingly awful. And not in a fun, campy, MST3K, way. It's awful in more of a dull, aching, why-didn't-the-dentist-prescribe-better-painkillers sort of way. Sure glad I didn't see that one in a theater... -- Grant Edwards grante Yow! I'm working under at the direct orders of WAYNE visi.com NEWTON to deport consenting adults! From dotancohen at gmail.com Wed Feb 13 03:05:26 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Wed, 13 Feb 2008 10:05:26 +0200 Subject: OT: Speed of light [was Re: Why not a Python compiler?] In-Reply-To: <8fGdnVvzR-CcBy_anZ2dnUVZ_rqlnZ2d@speakeasy.net> References: <6f-dnfwZwvz6Ui3anZ2dnUVZ_oOnnZ2d@speakeasy.net> <13r2p6aivk1no9a@corp.supernews.com> <880dece00802121311n77f73515ve7db8a931825d958@mail.gmail.com> <8fGdnVvzR-CcBy_anZ2dnUVZ_rqlnZ2d@speakeasy.net> Message-ID: <880dece00802130005v10b9fd47vb4df5ad826eaf58b@mail.gmail.com> On 13/02/2008, Erik Max Francis wrote: > And the rest of us just use SI. (And if you bring up the > _kilogram-force_, I'll just cry.) Don't cry, I just want to say that I've hated the kilogram-force almost as much as I've hated the electron-volt. Who is the lazy who comes up with these things? Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From k_r_a_j_kumar at yahoo.co.in Mon Feb 25 04:31:54 2008 From: k_r_a_j_kumar at yahoo.co.in (Raj kumar) Date: Mon, 25 Feb 2008 15:01:54 +0530 (IST) Subject: check a directory Message-ID: <526294.44700.qm@web8701.mail.in.yahoo.com> Hi all, I'm using following code... for x in listdir(path) some code..... but how i can check whether x is a directory or not? Because listdir() is giving all the files present in that path.... Thanks in advance. Did you know? You can CHAT without downloading messenger. Go to http://in.messenger.yahoo.com/webmessengerpromo.php/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From http Fri Feb 15 22:39:36 2008 From: http (Paul Rubin) Date: 15 Feb 2008 19:39:36 -0800 Subject: Passing a callable object to Thread References: <52465ed8-7d25-40ca-be69-478b308af879@u10g2000prn.googlegroups.com> <7xir0psq9l.fsf@ruckus.brouhaha.com> <452d63ea-3373-4393-9c28-38116f96d2e9@u10g2000prn.googlegroups.com> Message-ID: <7xzlu1bmdj.fsf@ruckus.brouhaha.com> Steve Holden writes: > Assuming you're right, what alternative would you suggest? Would it > allow parenthesized expressions to retain their customary meaning? It is kind of weird that there is even such a thing as a 1-tuple. From dont at spamon.me Mon Feb 4 12:45:39 2008 From: dont at spamon.me (USCode) Date: Mon, 04 Feb 2008 09:45:39 -0800 Subject: Client side GUI-like web framework ? Message-ID: Wouldn't it be handy if there was a web framework that allowed you to create pages and control the interface like you would using a client-side GUI framework such as Tkinter? The framework would need a small, fast web server that would automatically fire up when you ran your application and you then control the interface just like you would with client-side GUI widgets (within the limitations of browsers of course). It would handle all the complexities of HTTP, HTML, Javascript, etc. letting you focus on adding functionality to your application. Essentially you would be using the browser as your cross-platform client-side interface. You would just interact with all the widgets like trees, grids, paned windows, checkboxes, buttons, etc. There wouldn't happen to be anything like that available, would there? I've seen CherryPy but that doesn't quite seem to be what I described. Thanks! From pavlovevidence at gmail.com Tue Feb 26 08:23:12 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 26 Feb 2008 05:23:12 -0800 (PST) Subject: Article of interest: Python pros/cons for the enterprise References: <2f1527a7-2f66-44c7-9665-4d8ff01fa5ab@28g2000hsw.googlegroups.com><47bd4a24$0$25225$426a74cc@news.free.fr> <036e93e6-5840-4a3c-8642-67a0a9ec44f2@i7g2000prf.googlegroups.com> <784ec210-f389-4a15-b458-961100de9103@v3g2000hsc.googlegroups.com> <5d351937-e1bc-44ab-810d-11f226793b2e@b29g2000hsa.googlegroups.com> <345444fd-4c1c-460d-a402-5702b42f810e@c33g2000hsd.googlegroups.com> Message-ID: On Feb 26, 6:58 am, Paul Boddie wrote: > The Lisp > scene has also been plagued by an unnecessary deference to commercial > interests, which means that the hottest topic on comp.lang.lisp right > now is probably Paul Graham's much-anticipated but arguably > disappointing Lisp "successor", Arc, amongst the usual in-fighting and > parade-dampening. It looks like his main contribution was to get rid of superfluous parentheses. Which, admittedly, is no small thing for Lisp. Carl Banks From steve at REMOVE-THIS-cybersource.com.au Thu Feb 28 02:05:27 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 28 Feb 2008 07:05:27 -0000 Subject: How about adding rational fraction to Python? References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> <7x7igpn6lv.fsf@ruckus.brouhaha.com> Message-ID: <13scn9ncl7lds14@corp.supernews.com> On Wed, 27 Feb 2008 18:43:24 -0800, Paul Rubin wrote: > Steven D'Aprano writes: >> def pmean(data): # Paul Rubin's mean >> """Returns the arithmetic mean of data, unless data is all ints, in >> which case returns the mean rounded to the nearest integer less >> than the arithmetic mean.""" >> s = sum(data) >> if isinstance(s, int): return s//len(data) >> else: return s/len(data) > > Scheme and Common Lisp do automatic conversion and they thought out the > semantics rather carefully, and I think both of them return exact > rationals in this situation (int/int division). Potentially better than returning a float, but equally objectionable to all those insisting that int int should only return an int. > I agree with you that > using // as above is pretty weird and it may be preferable to raise > TypeError on any use of int/int (require either an explicit conversion, > or use of //). Then you have completely misunderstood my objection. It's not that // is weird, but that the semantics that you want by default: "return the mean for arbitrary numeric data, except for all ints, in which case return the mean rounded to the next smaller integer" is weird. Weird or not, if you want those semantics, Python gives you the tools to create it, as above. It's not even very much more work. But the normal semantics: "return the mean for arbitrary numeric data" should be easier, and with Python it is: def mean(data): return sum(data)/len(data) That does the right thing for data, no matter of what it consists of: floats, ints, Decimals, rationals, complex numbers, or a mix of all of the above. You want the pmean() case to be easy, and the mean() case to be hard, and that's what boggles my brain. -- Steven From kevin.p.dwyer at gmail.com Tue Feb 5 12:50:43 2008 From: kevin.p.dwyer at gmail.com (kdwyer) Date: Tue, 5 Feb 2008 09:50:43 -0800 (PST) Subject: Broke my IDLE! References: <1e6ec8dc-3fa4-4e75-86c1-26852ea30a65@n20g2000hsh.googlegroups.com> Message-ID: <1603d98e-a543-494d-acfe-e96b76c2fe37@j20g2000hsi.googlegroups.com> On Feb 5, 5:05 pm, "Adam W." wrote: > Tried running IDEL from the command prompt to get this: > > Traceback (most recent call last): > File "c:\Python25\Lib\idlelib\idle.pyw", line 21, in > idlelib.PyShell.main() > File "c:\Python25\lib\idlelib\PyShell.py", line 1404, in main > shell = flist.open_shell() > File "c:\Python25\lib\idlelib\PyShell.py", line 275, in open_shell > self.pyshell = PyShell(self) > File "c:\Python25\lib\idlelib\PyShell.py", line 813, in __init__ > OutputWindow.__init__(self, flist, None, None) > File "c:\Python25\lib\idlelib\OutputWindow.py", line 16, in __init__ > EditorWindow.__init__(self, *args) > File "c:\Python25\lib\idlelib\EditorWindow.py", line 125, in > __init__ > self.apply_bindings() > File "c:\Python25\lib\idlelib\EditorWindow.py", line 900, in > apply_bindings > text.event_add(event, *keylist) > File "c:\Python25\lib\idlelib\MultiCall.py", line 345, in event_add > widget.event_add(self, virtual, seq) > File "c:\Python25\lib\lib-tk\Tkinter.py", line 1357, in event_add > self.tk.call(args) > _tkinter.TclError: extra characters after detail in binding > > What do I need to edit and change? IIRC IDLE leaves some config files lying around in whatever was the current directory when it was executed. I think they're named idle.rc but I don't have a working install around to check on. It's possible that you need to clear these out to remove the binding. From michael.poeltl at univie.ac.at Thu Feb 21 09:41:09 2008 From: michael.poeltl at univie.ac.at (Michael Poeltl) Date: Thu, 21 Feb 2008 15:41:09 +0100 Subject: newbie in python In-Reply-To: References: <1d24edf1-78f1-420e-9ca5-ef7e810e20cc@72g2000hsu.googlegroups.com> <9f540144-9ff5-4c95-8b7d-c65df3d9a9ee@h25g2000hsf.googlegroups.com> Message-ID: <200802211541.09163.michael.poeltl@univie.ac.at> A big help for 'easily" learning python was and is "Learning Python" (a book written by Mark Lutz) after having studied this book you are able to "think in python" another book I like very much is "Core Python Programming" (written by Wesley Chun) regards michael On Thursday 21 February 2008 03:26:17 pm subeen wrote: > Dive into Python is a very good book but it's for people who have > experience in other languages. I liked the book. > Whatever book you read, please take a look at the Python Tutorial: > http://docs.python.org/tut/tut.html, it will help. > > regards, > Subeen. > http://love-python.blogspot.com/ > > On Feb 21, 6:01 pm, 7stud wrote: > > ctechnic... at gmail.com wrote: > > > Hi anyone > > > > > > I'm very interesed to learn python and really willing to do so,but > > > unfortunately dont know where to start, or what programs need to > > > install to start. > > > > > > Can someone help me to get in the right track, and get a good move? > > > > > > Thanks for all help > > > > If you're a good student or you have prior programming experience, get > > the book 'Learning Python', which just came out with a 3rd edition, so > > it is the most up to date book. > > > > If you are not such a good student or have no prior programming > > experience, and you want a gentler introduction to python, check out > > the book 'Python Programming for the Absolute Beginner(2nd Ed.)' From aisaac at american.edu Thu Feb 28 09:49:56 2008 From: aisaac at american.edu (Alan Isaac) Date: Thu, 28 Feb 2008 14:49:56 GMT Subject: Pythons & Ladders In-Reply-To: <0b1b0081-5eb9-41db-8039-1cb5727c2313@34g2000hsz.googlegroups.com> References: <75969097-e687-4092-af0d-fd6ce4df2f87@28g2000hsw.googlegroups.com> <0b1b0081-5eb9-41db-8039-1cb5727c2313@34g2000hsz.googlegroups.com> Message-ID: Benoit wrote: > Give > me something to do! Help to improve one of the experimental writers for docutils. IIRC, the ODT writer does not yet support figures and tables. http://www.rexx.com/~dkuhlman/odtwriter.html The rst2wordml writer appears to be getting its features in place, but when I last used it, some tinkering was required. You could work on adding features. http://docutils.sourceforge.net/sandbox/rst2wordml/readme.html If you get good enough a docutils, provide an option to have the number for the note be superscripted, like the note reference can be. fwiw, Alan Isaac From andrew at simx.co.uk Sat Feb 9 22:25:11 2008 From: andrew at simx.co.uk (Andrew Seaford) Date: Sun, 10 Feb 2008 03:25:11 GMT Subject: help with data extraction In-Reply-To: References: Message-ID: Amitava Maity wrote: > Hello, > > I have a data file (data.csv) that is something like this: > > data, Conductor, ACSR > data, diameter, 0.02862 > data, cross-section, 0.0004845 > data, weight, 1.621 > data, Mod, 7000000000 > data, Uts, 13450 > data, Coef, 0.0000193 > data, Cr, 20 > data, span, 350 > data, Wind pres, 0 > data, temp, 32 > data, ten, 3326 > cond, Final wind press, 0, Final temp, 4 > cond, Final wind press, 30, Final temp, 4 > cond, Final wind press, 45, Final temp, 32 > cond, Final wind press, 0, Final temp, 64 > section, 234, 267, 289, 197 > > I need to to extract the third element from the rows with 'data' as > the first element, the third and fifth element from the rows with > 'cond' as the first element and > all the elements following the 'section' element in the rows with > 'section' as the first element. > > here is the code used to extract the data: > > import csv > > keys = ["type", "d", "x", "c", "m", "u", "a", "tcr", "s", "wi", "ti", "Ti"] > values = [] > wind = [] > temp = [] > sec = [] > > > reader = csv.reader(open("data.csv", "rb")) > > for row in reader: > if row[0] == 'data': values.append(row[2]) > if row[0] == 'cond': wind.append(row[2]), temp.append(row[4]) > if row[0] == 'section': sec = row[1:] > > > inputs = dict(zip(keys, values)) > conditions = dict(zip(wind, temp)) > condition = tuple(conditions.items()) > > print inputs, condition, sec > > What I can't understand here is why the 1st row with 'cond' data and > 1st element with 'section' data being skipped. > > What is the fix? > > thanks in advance, > The code does not skip the 1st row with 'cond' and 'section'. The file is read correctly and the data is appended to the wind and temp lists. Resulting in the two lists below wind = [0,30,45,0] temp = [4,4,32,64] The line conditions = dict(zip(wind, temp)) creates a dictionary using the wind and temp lists. In a dictionary each key is unique. The first key is 0 which is assigned the value 4. The second key is 30 with the value 4. The third key is 45 with the value 32. The key 0 is assigned a new value of 64. The result is that the dictionary has three key value pairs, not four. Andrew Seaford Simulation Director Simulation eXpertise web www.simx.co.uk email andrew at simx.co.uk From bbxx789_05ss at yahoo.com Mon Feb 18 00:10:19 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Sun, 17 Feb 2008 21:10:19 -0800 (PST) Subject: CSV module: incorrectly parsed file. References: <4733861b-8128-4cec-9d0b-6543e923a0e3@s13g2000prd.googlegroups.com> <0e16f1bb-fdb7-4bd6-8f25-6ffa13c3e69f@k2g2000hse.googlegroups.com> Message-ID: On Feb 17, 9:11?pm, 7stud wrote: > On Feb 17, 7:09?pm, Christopher Barrington-Leigh > > > > wrote: > > Here is a file "test.csv" > > number,name,description,value > > 1,"wer","tape 2"",5 > > 1,vvv,"hoohaa",2 > > > I want to convert it to tab-separated without those silly quotes. Note > > in the second line that a field is 'tape 2"' , ie two inches: there is > > a double quote in the string. > > > When I use csv module to read this: > > > import sys > > outf=open(sys.argv[1]+'.tsv','wt') > > import csv > > reader=csv.reader(open(sys.argv[1], "rb")) > > for row in reader: > > ? ? outf.write('\t'.join([rr.strip() for rr in row]) +'\n') > > > it mangles it, messing up the double double-quote. > > Can anyone help me? How do I use CSV to get it right? > > Tjhanks! > > c > > Try this: > > infile = open('data.txt') > outfile = open('outfile.txt', 'w') > > for line in infile: > ? ? pieces = line.strip().split(',') > > ? ? data = [] > ? ? for piece in pieces: > ? ? ? ? if piece[0] == '"': > ? ? ? ? ? ? data.append(piece[1:-2]) > ? ? ? ? else: > ? ? ? ? ? ? data.append(piece) > > ? ? out_line = '%s\n' % '\t'.join(data) > ? ? outfile.write(out_line) Whoops. The line: data.append(piece[1:-2]) should be: data.append(piece[1:-1]) From jzgoda at o2.usun.pl Wed Feb 20 08:17:23 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Wed, 20 Feb 2008 14:17:23 +0100 Subject: is this data structure build-in or I'll have to write my own class? In-Reply-To: References: Message-ID: Jorge Vargas napisa?(a): > - attribute access (or index) > - maintain the order (for iter and print) > - be mutable. These are all attributes of standard Python lists. > in case there isn't one. I was thinking having a base class like Bunch > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308 and on > top of that keeping a list of the keys and pop/push to the list when > adding/deleting items. I don't like this idea because I'll have to > keep each key twice. (in the list and in __dict__, is this the only > way of doing it? What is your objective? From the description of this recipe I cann't get your use case. -- Jarek Zgoda Skype: jzgoda | GTalk: zgoda at jabber.aster.pl | voice: +48228430101 "We read Knuth so you don't have to." (Tim Peters) From jr9445 at ATT.COM Tue Feb 5 10:28:23 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Tue, 5 Feb 2008 09:28:23 -0600 Subject: Using Regular Expressions to Parse SQL In-Reply-To: References: Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of ct60 at aol.com > Sent: Tuesday, February 05, 2008 9:31 AM > To: python-list at python.org > Subject: Using Regular Expressions to Parse SQL > > > My pattern does not even come close. > > Any help would be greatly appreciated. My goal is to analyse a large > number of SQL querys to try to identify the join field and see where > indexing might make sense. > > While I am mostly interested in understanding regular expressions, I > would also be interested in knowing about any Python SQL parsers out > there. Python's regexes are a tad odd compared to Perl (or Perl's regexes are odd. Relativity.) You need re.DOTALL to handle newlines in the sql: DOTALL Make the "." special character match any character at all, including a newline; without this flag, "." will match anything except a newline. import re s= ''' FROM ((qry_Scores_Lookup1 INNER JOIN CSS_Rpt1 ON (qry_Scores_Lookup1.desc = CSS_Rpt1.desc) AND (qry_Scores_Lookup1.lastcdu = CSS_Rpt1.lastcdu))''' pat = r"(^|\s+)FROM\s.+\s(?:INNER|LEFT|RIGHT)\s+JOIN\s.+\sON\s+((\s*(?:\S+)\s* =\s*(?:\S+))(?:\s+|\s+AND\s+|$))+" m = re.compile(pat, re.DOTALL).match(s) if m: print m ('(qry_Scores_Lookup1.desc = CSS_Rpt1.desc) ', '(qry_Scores_Lookup1.desc = CSS_Rpt1.desc)') You should be able to tweak the regex to get the exact matches you want. An alternative to writing a lengthy regex might be to just grab everything after the ON and then string split on "AND". ***** The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA623 From jeff at schwabcenter.com Fri Feb 15 14:13:00 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Fri, 15 Feb 2008 11:13:00 -0800 Subject: Floating point bug? In-Reply-To: <9b166b3d-89df-4f26-956a-abbd391167e7@i12g2000prf.googlegroups.com> References: <6eba298e-6888-462a-afa7-54fae02c3dce@y5g2000hsf.googlegroups.com> <61ibo1F1uqso2U1@mid.uni-berlin.de> <188be6e9-bc05-4a72-924b-1de184980002@n58g2000hsf.googlegroups.com> <9b166b3d-89df-4f26-956a-abbd391167e7@i12g2000prf.googlegroups.com> Message-ID: Zentrader wrote: > I disagree with this statement > But that doesn't change the fact that it will expose the same > rounding-errors as floats do - just for different numbers. > The example used has no rounding errors. I think we're using the term "rounding error" to mean different things. If the value 1/3 is represented as a finite sequence of threes divided by a power of ten (e.g. 0.3333333333333333333333333333), then it is actually representing a different value than the original 1/3 (3333333333333333333333333333/10000000000000000000000000000). This is what most of us mean by "rounding error." There are data types than can represent rational numbers exactly, such that 1 / 3 * 3 = 1. > For anything less that 28 > significant digits it rounds to 1.0. I'm not sure what you mean here. Do you mean that Decimal can represent any sequence of up to 28 decimal digits without any loss in precision? No one disputes that. > With floats 1.0/3 yields > 0.33333333333333331<-- on my machine. Right, that is != 1/3. But if the last digit were a 3, the number still would not be 1/3, only a different approximation of it. > Also you can compare two > decimal.Decimal() objects for equality. With floats you have to test > for a difference less than some small value. A small margin of error (epsilon) is required for both Decimal and floats. Both of these data types have "floating points;" they just use different radixes. Particular sorts of rounding-errors have become acceptable in base-10 arithmetic within certain (mainly financial) contexts, so Decimal is preferable for calculations in those contexts. For the same reason, a major U.S. stock exchange switched from base-2 to base-10 arithmetic a few years ago. There's nothing inherently more accurate about base-10. > BTW, a college professor > who also wrote code for a living made this offhand remark "In general > it is best to multiply first and then divide." Good general advice. It is best to keep track of how many significant digits remain in whatever base is being used. "M before D" may help preserve sig. digits, but it is not a substitute for knowing how much error each calculation introduces. From ilias at lazaridis.com Sat Feb 16 20:25:35 2008 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Sat, 16 Feb 2008 17:25:35 -0800 (PST) Subject: TRAC - Trac, Project Leads, Python, and Mr. Noah Kantrowitz (sanitizer) References: <3d40196b-b1c8-4e18-92f0-7ce5a5a38853@u72g2000hsf.googlegroups.com> Message-ID: <1500d101-ed2a-423a-9f93-41d0a4a3641e@k2g2000hse.googlegroups.com> On 16 ???, 19:15, Jeff Schwab wrote: > Ilias Lazaridis wrote: > > Essence: > > Spam spam spam spam... > > I just looked at your resume. http://lazaridis.com/resumes/lazaridis.html (need to update it, lot's of irrelevant stuff, should focus on my failures) > What is Abstract Project Management? I've mentioned "abstract _product_ management" Don't know exactly, I've never tried to articulate the meaning which I've internally. You could extract the meaning from "Abstract Base Class" or "Abstractness" in general. Something like "universal product management". Or managing a product without having many specific information about it. Something like this _possibly_: http://case.lazaridis.com/wiki/KomodoAudit From divinmarchese at gmail.com Tue Feb 12 16:14:36 2008 From: divinmarchese at gmail.com (DiMar) Date: Tue, 12 Feb 2008 13:14:36 -0800 (PST) Subject: Unicode char replace References: <43028c04-d9bb-4708-b08e-8c6fd2c113ba@1g2000hsl.googlegroups.com> <47b20956$0$2660$9b622d9e@news.freenet.de> Message-ID: > May I ask why? Of course! I have to find that string into a list of strings. This list includes one, using » Thanks! :) From rconradharris at gmail.com Thu Feb 14 12:31:25 2008 From: rconradharris at gmail.com (Rick Harris) Date: Thu, 14 Feb 2008 09:31:25 -0800 (PST) Subject: Copying weakrefs Message-ID: <7eac1891-66b2-4716-86f1-f85292b1c822@e25g2000prg.googlegroups.com> I am working with an object, Context, that maintains an identity map by using the weakref.WeakValueDictionary. I would like to clone this Context object (and objects that may have a Context object) using copy.deepcopy(). When I try to do this, the deep copy operation recurses down to the WeakValueDictionary, down to the KeyedRef subclass of ref, and then fails. It seems that copy.copy() and copy.deepcopy() operations on weakrefs just won't work. The failure can be replicated with this (much simpler) scenario: >>> import weakref, copy >>> class Test(object): pass >>> t = Test() >>> wr = weakref.ref(t) >>> wr_new = copy.copy(wr) # Fails, not enough args to __new__ Anybody out there have some insight into this? Thanks Rick From ggpolo at gmail.com Thu Feb 7 20:15:21 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 7 Feb 2008 23:15:21 -0200 Subject: Microsoft's challenger to Python In-Reply-To: <880dece00802071708m618a8750w5f5709c57ec0ec59@mail.gmail.com> References: <47AB9D50.5050503@bmm.com> <880dece00802071708m618a8750w5f5709c57ec0ec59@mail.gmail.com> Message-ID: 2008/2/7, Dotan Cohen : > On 08/02/2008, Peter Dilley wrote: > > I am not, however, an in depth language nutter, so would > > appreciate any of our more learned readers comments. > > > Looks like MS forgot E and E and went straight for E this time. > I couldn't understand what you said, maybe that a E language doesnt yet exist? It does: http://www.erights.org/ > Dotan Cohen > > http://what-is-what.com > http://gibberish.co.il > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > > A: Because it messes up the order in which people normally read text. > Q: Why is top-posting such a bad thing? > > -- > http://mail.python.org/mailman/listinfo/python-list -- -- Guilherme H. Polo Goncalves From pavlovevidence at gmail.com Mon Feb 4 13:12:14 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 4 Feb 2008 10:12:14 -0800 (PST) Subject: Unexpected timing results with file I/O References: <13qeb3upn3qic61@corp.supernews.com> Message-ID: <53db8fec-cc64-46c3-993f-e5191ae4261e@v4g2000hsf.googlegroups.com> On Feb 4, 12:53 pm, rdahlstrom wrote: > On Feb 4, 10:17 am, Steven D'Aprano > > > cybersource.com.au> wrote: > > After reading an earlier thread about opening and closing lots of files, > > I thought I'd do a little experiment. > > > Suppose you have a whole lot of files, and you need to open each one, > > append a string, then close them. There's two obvious ways to do it: > > group your code by file, or group your code by procedure. > > > # Method one: grouped by file. > > for each file: > > open the file, append the string, then close it > > > # Method two: grouped by procedure. > > for each file: > > open the file > > for each open file: > > append the string > > for each open file: > > close the file > > > If you have N files, both methods make the same number of I/O calls: N > > opens, N writes, N closes. Which is faster? > > > Intuitively, the first method has *got* to be faster, right? It's got one > > loop instead of three and it doesn't build an intermediate list of open > > file objects. It's so *obviously* going to be faster that it is hardly > > worth bothering to check it with timeit, right? > > > Well, I wouldn't be writing unless that intuitive result was wrong. So > > here's my test results: > > > Method 1: > > > >>> import timeit > > >>> names = ['afile' + str(n) for n in range(1000)] > > >>> T = timeit.Timer('''for name in names: > > > ... fp = open(name, 'a'); fp.write('xyz\\n'); fp.close() > > ... ''', 'from __main__ import names')>>> min(T.repeat(6, 500)) > > > 17.391216039657593 > > > Method 2: > > > >>> for name in names: # reset the files to an empty state. > > > ... fp = open(name, 'w'); fp.close() > > ...>>> T = timeit.Timer('''files = [open(name, 'a') for name in names] > > > ... for fp in files: > > ... fp.write('xyz\\n') > > ... for fp in files: > > ... fp.close() > > ... ''', '''from __main__ import names''')>>> min(T.repeat(6, 500)) > > > 16.823362112045288 > > > Surprisingly, Method 2 is a smidgen faster, by about half a second over > > 500,000 open-write-close cycles. It's not much faster, but it's > > consistent, over many tests, changing many of the parameters (e.g. the > > number of files, the number of runs per timeit test, etc.). > > > I'm using Linux and Python 2.5. > > > So, what's going on? Can anyone explain why the code which does more work > > takes less time? > > > -- > > Steven > > The code that does more work takes more time. The second one does > quite a bit less work. Think of it like this: > > You have 500,000 people to fit through a door. Here are your options: > > 1. For each person, open the door, walk through the door, then close > the door. > 2. Open the door, allow everyone to walk through, then close the > door. > > Which one would you say would be a more efficient way to fit 500,000 > people through the door? Bad analogy. A better analogy would be if each person has their own door to walk through. My hunch is that is has to do with the OS I/O scheduling. Closing a file triggers a cache flush, which in turn triggers the I/O to schedule a write to disk; the OS scheduler is perhaps more efficient (for a given number of total writes) when it can combine many writes at the same time. Carl Banks From arnodel at googlemail.com Sun Feb 3 04:55:19 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 3 Feb 2008 01:55:19 -0800 (PST) Subject: Python feature request : operator for function composition References: <83631748-4190-47f6-acff-6afb363c3ea5@c23g2000hsa.googlegroups.com> Message-ID: <9b38559f-b99d-4859-9daa-b905b054f27c@u10g2000prn.googlegroups.com> On Feb 3, 9:43?am, Kay Schluehr wrote: > On 3 Feb., 10:13, Arnaud Delobelle wrote: > > > > > On Feb 3, 5:09 am, Kay Schluehr wrote: > > > > As you know, there is no operator for function composition in Python. > > > When you have two functions F and G and ?want to express the > > > composition F o G you have to create a new closure > > > > lambda *args, **kwd: F (G (*args, **kwd)) > > > > or you write a composition in functional style > > > > compose( F, G ) > > > > None of these solutions is particular terse. > > > > Proposal > > > ------------- > > > I want to propose overloading the logical __and__ operator i.e. '&' > > > for functions s.t. F & G means "compose(F,G)". This suggestion is non- > > > conflicting since & is not used as an operator in combination with > > > function objects yet: given a function object F and an arbitrary > > > object X the combination F & X raises a TypeError when evaluated. > > > > Alternatives > > > ----------------- > > > One could use other unused operators like F << G or F * G to write > > > terse function composition expressions. I' m not sure which one is > > > best and would use the proposed & if no one presents arguments against > > > it. > > > What about other callable objects? > > > -- > > Arnaud > > Supporting general callables would be very fine. I thing a callable > ABC with two protocols named __call__ and __compose__ would be most > adequate. I'm just not sure if Python 2.X requires a more ad hoc > implementation for builtin callable types? On the level of user > defined classes a bundling between __call__ and __compose__ shall > remain optional ( unlike e.g. the dependency between __iter__ and > __next__ for iterables ). This would conflict with the fact that the operators you suggest for composition can already be overloaded for other purposes. -- Arnaud From jeff at schwabcenter.com Tue Feb 26 12:37:16 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Tue, 26 Feb 2008 09:37:16 -0800 Subject: is there enough information? In-Reply-To: <8e2ce70d-0c7d-4d25-a646-3c48f2cfc839@q78g2000hsh.googlegroups.com> References: <56783fab-c5c5-4e42-a0fb-519f75beb65a@72g2000hsu.googlegroups.com> <0f240e82-04de-497f-a9aa-07458fc97235@b1g2000hsg.googlegroups.com> <03d54be8-b1a8-455b-9e1f-c75626aedc3e@72g2000hsu.googlegroups.com> <8e2ce70d-0c7d-4d25-a646-3c48f2cfc839@q78g2000hsh.googlegroups.com> Message-ID: <6aWdnZhVGbG501nanZ2dnUVZ_q-jnZ2d@comcast.com> castironpi at gmail.com wrote: > On Feb 26, 10:59 am, Preston Landers wrote: >> On Feb 26, 1:45 am, castiro... at gmail.com wrote: >> >>> Two options occurred to me, which the first showed up in the earlier >>> extremely skeletal and cryptic post: >> Perhaps you would be more likely to get the kind of help you seem to >> want >> if you refrained from posting "cryptic and skeletal" messages. The >> fact that many >> other people have pointed this out to you as of late would tend to >> suggest >> you are trolling, i.e. intentionally trying to foster miscommunication >> and threads >> that do nothing to advance anyones understanding. >> >> And regarding your other recent post about trying to find a "solution" >> to the "problem" >> of immutable types... Due to the above reasons you are unlikely to >> influence the >> design of the core language with half-baked stream of consciousness >> ramblings. These >> belong in your LiveJournal, not in c.l.python. >> >> If you have a problem you need help with, please read this entire >> document about 3 times >> before posting anything else: >> >> http://catb.org/~esr/faqs/smart-questions.html >> >> Specifically this: >> >> http://catb.org/~esr/faqs/smart-questions.html#beprecise >> >> and this: >> >> http://catb.org/~esr/faqs/smart-questions.html#goal > > Ugh, very well. You call for an explanation. > > Back home, the original post would be interesting, so I wrote it. > Whatever reactions other people have to them is information that is > unavailable to me. I don't know you. I'm rather irked by a > proportion of posts, but for my part, it's hard to get me to point a > finger. > > I am not a troll. I want a sustainable, healthy, productive, > educational, informative relationship with frequenters of c.l.p, the > Python community at large, and anyone who has anything non-negative to > contribute. If you are wanting to see how I react to hostility, just > ask. I'll fake it for you, but only for a second at a time. Wow. I sure hope I don't come across like castiron does here. > Now, what help is it that you believe I seem to want? All I asked for > was, ideas. It's a little difficult for me to interpret your code, partly because I am nbt very familiar with Python's support for concurrency. But what are you trying to a achieve? You mentioned: "I recently ran into a case (* would that be helpful to describe here?) where thread1 had to do something, thread2 had to do something after that, and thread1 had to wait for that, then do something else, and thread2 again had to wait before starting the first thing again." This is ordinarily called a Producer-Consumer model. It is often implemented using semaphores. Googling "python semaphore" turns up this documentation: http://www.python.org/doc/lib/semaphore-objects.html That page, in turn, links to an example of the proper use of semaphores in Python. Does that help? From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Feb 14 08:22:01 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 14 Feb 2008 14:22:01 +0100 Subject: Cannot understand error message In-Reply-To: <_YadncvbV-vViinanZ2dnUVZ8q2dnZ2d@bt.com> References: <215d3d59-2204-44b0-bfdb-c7de8fb1f12f@e23g2000prf.googlegroups.com> <47b412dc$0$4273$426a74cc@news.free.fr> <_YadncvbV-vViinanZ2dnUVZ8q2dnZ2d@bt.com> Message-ID: <47b4403d$0$10887$426a74cc@news.free.fr> Bill Davy a ?crit : > "Bruno Desthuilliers" > wrote in message news:47b412dc$0$4273$426a74cc at news.free.fr... (snip) >>> Many thanks for the help. Must get a bigger screen and new eyes. >> Or a better code editor. > > I just grabbed what was on the shelf. Is there a Python plug-in for MSVC? > ;-) Don't know, but I'm not sure if MSVC qualifies as a "better code editor" anyway !-) From kyosohma at gmail.com Thu Feb 21 20:00:41 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 21 Feb 2008 17:00:41 -0800 (PST) Subject: Python on Windows Help References: <2337913e-5f5c-4f3d-aaa2-01d50dc5f457@v3g2000hsc.googlegroups.com> Message-ID: <9e54feaa-0681-472a-bbf2-1cdb20ea15f0@f47g2000hsd.googlegroups.com> On Feb 21, 10:09 am, msm... at carilion.com wrote: > I've written the following script based on information I have found on > the web. The purpose of the script is to start an HTTP listener on > the machine it's running on that will give status on a particular > service running on that system. I've tried to create this as a > service on the windows server it's running on, and it will install > fine. The problem I'm having is that the service will not stop when I > tell it to. Any help that anyone could provide would be greatly > appreciated. I'm new to python so please let me know if there is a > more efficient way to do what I'm trying to do. The code follows: > > import win32service > import win32serviceutil > import wmi > from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler > > class BlobCheck(win32serviceutil.ServiceFramework): > _svc_name_ = "BlobCheck" > _svc_display_name_ = "Epic Blob Checker" > _svc_description_ = "Checks the Epic Blob Service and Creates an HTTP > listener that can be polled for status" > > def __init__(self,args): > win32serviceutil.ServiceFramework.__init__(self,args) > self.isAlive = True > > def SvcDoRun(self): > import servicemanager > c = wmi.WMI() > > while self.isAlive: > class RequestHandler(BaseHTTPRequestHandler): > def _writeheaders(self): > self.send_response(200) > self.send_header('Content-type', 'text/html') > self.end_headers() > > def do_HEAD(self): > self._writeheaders() > > def do_GET(self): > self._writeheaders() > running = c.Win32_Process (name="notepad.exe") > if running: > self.wfile.write("""Monitor > Kool-Aid!!!""") > else: > self.wfile.write("""Monitor > Oh No!!!""") > > serveraddr = ('', 12345) > srvr = HTTPServer(serveraddr, RequestHandler) > srvr.handle_request() > > def SvcStop(self): > import servicemanager > > servicemanager.LogInfoMsg("aservice - Recieved stop signal") > self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) > self.isAlive = False > > if __name__ == '__main__': > win32serviceutil.HandleCommandLine(BlobCheck) I would recommend cross-posting this to the PyWin32 mailing list. They'll either know what to do or tell you you can't. You can sign up here: http://mail.python.org/mailman/listinfo/python-win32 Mike From saetaes at gmail.com Tue Feb 26 19:54:40 2008 From: saetaes at gmail.com (Mike M) Date: Tue, 26 Feb 2008 19:54:40 -0500 Subject: Portable linux python install Message-ID: <8552c3a30802261654g3e9c5560xbe9750ab042b0241@mail.gmail.com> Hello, I've been digging around the list archives and I haven't found a good answer to this, so I was hoping someone on this list could help me out. Here's my conundrum: I have a python application which I'd like to distribute to thousands of machines in our server farm. The good news is, all of the machines I'd like to run this application on are running Red Hat Linux. The bad news is, they are various versions of RHEL - some Red Hat 7.3 and RHEL 2.1, a lot more RHEL 3, even more RHEL 4 and some RHEL 5 to boot. Because of this variation of base installs of Python (1.5 up to 2.4 and everywhere in-between), I was wondering if there was a way to compile a common python 2.5 that I could then drop into the /opt directory and run from there, leaving the system python in place. I understand there may be some glibc compatibility issues, but hopefully that is as simple as installing the appropriate compat-* libraries. Is this possible? If so, what are the steps to do it? Has anyone ever tried to do something similar? I apologize if this is a ridiculously simple question, but things like this always throw me for a loop. Thanks in advance for any assistance or pointers. Mike From castironpi at gmail.com Thu Feb 14 19:26:25 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 14 Feb 2008 16:26:25 -0800 (PST) Subject: XML pickle References: <686a4012-1c9e-456e-973c-c1e396f4c060@s8g2000prg.googlegroups.com> <47B3E3A3.1070205@behnel.de> <47B488FD.1090502@behnel.de> <47B49B3E.3060609@behnel.de> <37a7ec38-d210-490f-b2eb-5db6f6ac6732@e10g2000prf.googlegroups.com> <878x1n13ge.fsf@benfinney.id.au> Message-ID: <39282a9c-e6f6-47d1-a6ca-0910144dcea8@i29g2000prf.googlegroups.com> Great! -- ?\ ? ? ? ? ?"I moved into an all-electric house. I forgot and left the | ? `\ ? porch light on all day. When I got home the front door wouldn't | _o__) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? open." ?-- Steven Wright | Ben Finney From mrstevegross at gmail.com Thu Feb 21 16:43:26 2008 From: mrstevegross at gmail.com (mrstephengross) Date: Thu, 21 Feb 2008 13:43:26 -0800 (PST) Subject: Return value of an assignment statement? Message-ID: <6d945394-739e-4c47-ad71-faaab8f9d566@34g2000hsz.googlegroups.com> Hi all. In C, an assignment statement returns the value assigned. For instance: int x int y = (x = 3) In the above example, (x=3) returns 3, which is assigned to y. In python, as far as I can tell, assignment statements don't return anything: y = (x = 3) The above example generates a SyntaxError. Is this correct? I just want to make sure I've understood the semantics. Thanks, --Steve From theller at ctypes.org Wed Feb 27 08:12:06 2008 From: theller at ctypes.org (Thomas Heller) Date: Wed, 27 Feb 2008 14:12:06 +0100 Subject: Why this ref leak? In-Reply-To: <62l2q4F2315laU1@mid.uni-berlin.de> References: <62l2q4F2315laU1@mid.uni-berlin.de> Message-ID: Gerhard H?ring schrieb: > import sys > > def foo(): > class C(object): > pass > > foo() > print ">>", sys.gettotalrefcount() > foo() > print ">>", sys.gettotalrefcount() > foo() > print ">>", sys.gettotalrefcount() > > >> 21366 > >> 21387 > >> 21408 > [9779 refs] > > Both Python 2.4 and 2.5 don't clean up properly here. Why is this? > Aren't classes supposed to be garbage-collected? > > -- Gerhard Replace "foo()" with "foo(); gc.collect()" and the refcounts are stable. Tested the python 2.6 from trunk. Thomas From jaywgraves at gmail.com Wed Feb 20 09:21:14 2008 From: jaywgraves at gmail.com (jay graves) Date: Wed, 20 Feb 2008 06:21:14 -0800 (PST) Subject: Automating GUI interaction with Python References: Message-ID: <06b8f8c9-035d-4166-91f6-758c796143d1@i29g2000prf.googlegroups.com> On Feb 20, 5:37 am, "Ryan Ginstrom" wrote: > > On Behalf Of jorma kala > > Is there a python library or bindings to a library in some > > other language for automating GUI interaction (the kind of > > functionality provided by Autoit for instance). > > What I need to do is very simple GUI automation : moving the > > mouse cursor to and from specified screen coordinates, clicking, etc. > > Thanks a lot. > > For Windows, try pyWinAutohttp://pywinauto.openqa.org/ dogtail is another http://people.redhat.com/zcerza/dogtail/ ... Jay Graves From jon+usenet at unequivocal.co.uk Mon Feb 4 10:03:44 2008 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 4 Feb 2008 15:03:44 GMT Subject: Getting Python to fork? References: <4a32de90-dbdd-49da-ab17-93037d3229f7@p69g2000hsa.googlegroups.com> Message-ID: On 2008-02-04, Bernard wrote: > #Fork and commit suicide > if os.fork(): > sys.exit(0) I'm pretty sure that should be os._exit(0) > #What to do in parent process This is now the child process. > sys.stdin = open('/dev/null') > sys.stdout = open('/dev/null', 'w') > sys.stderr = open('/dev/null', 'w') I think that's changing Python's idea of stdin etc but not the operating system's idea of them. You won't be closing the original file descriptors, and if you run any subprocesses they will end up with the original stdin/out/err. Unless sys.stdin is more magic than I'm aware of. From steve at REMOVE-THIS-cybersource.com.au Wed Feb 27 21:47:45 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 28 Feb 2008 02:47:45 -0000 Subject: How about adding rational fraction to Python? References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <7x63wbez2b.fsf@ruckus.brouhaha.com> <13sc3ccds5ap5a9@corp.supernews.com> <7x1w6xrfxe.fsf@ruckus.brouhaha.com> Message-ID: <13sc86hjaabtu9c@corp.supernews.com> On Wed, 27 Feb 2008 18:08:29 -0800, Paul Rubin wrote: > Steven D'Aprano writes: >> When it comes to mixed arithmetic, it's just too darn inconvenient to >> forbid automatic conversions. Otherwise you end up either forbidding >> things like 1 + 1.0 on the basis that it isn't clear whether the >> programmer wants an int result or a float result, > > You can parse 1 as either an integer or a floating 1, so 1 + 1.0 can be > correctly typed as a float. However (for example), len(x) is always an > int so len(x) + 1.0 would be forbidden. Okay, that's just insane, making distinctions between literals and variables like that. 1 + 1.0 # okay x = 1 x + 1.0 # is this okay or not? who knows? len('s') + 1.0 # forbidden I am so glad you're not the designer of Python. >> or else even more complex rules ("if the left operator is an int, and >> the result of the addition has a zero floating-point part, then the >> result is an int, > > That is ugly and unnecessary. Which was my point. -- Steven From steve at holdenweb.com Sun Feb 3 07:18:25 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 03 Feb 2008 07:18:25 -0500 Subject: Does anyone else use this little idiom? In-Reply-To: References: Message-ID: <47A5B111.2080309@holdenweb.com> Jeff Schwab wrote: > How miller.paul.w at gmail.com wrote: >> Ruby has a neat little convenience when writing loops where you don't >> care about the loop index: you just do n.times do { ... some >> code ... } where n is an integer representing how many times you want >> to execute "some code." >> >> In Python, the direct translation of this is a for loop. When the >> index doesn't matter to me, I tend to write it as: >> >> for _ in xrange (1,n): >> some code >> >> An alternative way of indicating that you don't care about the loop >> index would be >> >> for dummy in xrange (1,n): >> some code >> >> But I like using _ because it's only 1 character and communicates well >> the idea "I don't care about this variable." >> >> The only potential disadvantages I can see are threefold: >> >> 1. It might be a little jarring to people not used to it. I do admit >> it looks pretty strange at first. >> >> 2. The variable _ has special meaning at the interactive interpreter >> prompt. There may be some confusion because of this. >> >> 5. Five is right out. (ob Holy Grail reference, of course. :-) >> >> So, I guess I'm wondering if anyone else uses a similar idiom and if >> there are any downsides to it that I'm not aw > > Would something like this be acceptable? It still requires a loop > variable, plus an extra line of code per loop, plus a one-time class > definition (and import into each client module), and it's probably > slower than "for dummy in range." The syntax might be more inuitive > than "dummy" or "_" in a for loop, though. > > class Go: > def __init__(self, count): > self.count = count > > def again(self): > if self.count <= 0: > return False > self.count -= 1 > return True > > go = Go(3) > while go.again(): > print "hello" One could rename the again() method __call__(), allowing the even more horrible but less verbose while Go(3)(): print "hello" That'd confuse the newbies! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From stefan_ml at behnel.de Sat Feb 16 02:41:45 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 16 Feb 2008 08:41:45 +0100 Subject: Help Parsing an HTML File In-Reply-To: <15f9198f-fa2a-4f4f-8f87-7402b03743e1@s13g2000prd.googlegroups.com> References: <15f9198f-fa2a-4f4f-8f87-7402b03743e1@s13g2000prd.googlegroups.com> Message-ID: <47B693B9.3040007@behnel.de> egonslokar at gmail.com wrote: > I have a single unicode file that has descriptions of hundreds of > objects. The file fairly resembles HTML-EXAMPLE pasted below. > > I need to parse the file in such a way to extract data out of the html > and to come up with a tab separated file that would look like OUTPUT- > FILE below. > > =====OUTPUT-FILE===== > /please note that the first line of the file contains column headers/ > ------Tab Separated Output File Begin------ > H1 H2 DIV Segment1 Segment2 Segment3 > Ros?H1-1 Ros?H2-1 Ros?DIV-1 Ros?SegmentDIV1-1 Ros?SegmentDIV2-1 > ------Tab Separated Output File End------ > > =====HTML-EXAMPLE===== > ------HTML Example Begin------ > > >

Ros?H1-1

>

Ros?H2-1

>
Ros?DIV-1
>
Ros?SegmentDIV1-1

>
Ros?SegmentDIV2-1

>
Ros?SegmentDIV3-1

>
>
> > > ------HTML Example End------ Now, what ugly markup is that? You will never manage to get any HTML compliant parser return the "segmentX" stuff in there. I think your best bet is really going for pyparsing or regular expressions (and I actually recommend pyparsing here). Stefan From nagle at animats.com Tue Feb 5 16:25:28 2008 From: nagle at animats.com (John Nagle) Date: Tue, 05 Feb 2008 13:25:28 -0800 Subject: Very weird behavior in MySQLdb "execute" In-Reply-To: References: <47a76661$0$36336$742ec2ed@news.sonic.net> Message-ID: <47a8d2c8$0$36375$742ec2ed@news.sonic.net> Paul Boddie wrote: > On 4 Feb, 20:30, John Nagle wrote: >> This has me completely mystified. Some SELECT operations performed through >> MySQLdb produce different results than with the MySQL graphical client. >> This failed on a Linux server running Python 2.5, and I can reproduce it >> on a Windows client running Python 2.4. Both are running MySQL 2.5. > > I'm not actively using MySQL at the moment, so my comments are just > passing remarks that may or may not help. > >> The table involved is: >> >> CREATE TABLE domaincache >> ( >> domain VARCHAR(255) NOT NULL UNIQUE PRIMARY KEY, > > Passing remark #1: I believe that "domain" is a reserved word in SQL. Not since SQL-99. DOMAIN stopped being a reserved word in SQL-2003. See "http://developer.mimer.com/validator/sql-reserved-words.tml" It is not a reserved word in MySQL. >> >> select * from domaincache where domain = "adwords.google.com" >> or >> select * from domaincache where domain = "google.com" > > Passing remark #2: In SQL, double quotes are usually used to "protect" > identifiers from being recognised as reserved words. Now, I believe > that MySQL can be quite relaxed about this, but this could be an issue > if some conformance mode gets set somewhere. The SQL standard requires single quotes, while MySQL allows both. Actually, the real code lets the MySQLdb interface do the quoting; this was just a manual test. > Cheap shot: I guess this is why I'm using PostgreSQL. Actually, most of the above comments were totally irrelevant. The real problem (discussed in the Python newsgroup) was a failure to COMMIT after a SELECT. MySQL InnoDB databases run in "repeatable read" mode, and if you have a long-running process and don't COMMIT after a SELECT, the results of redoing a SELECT will not change, regardless of other updates to the table. So it really is necessary to COMMIT after SELECT to see new updates to the database, even when not making changes. John Nagle From joelcarrier at gmail.com Fri Feb 22 11:35:03 2008 From: joelcarrier at gmail.com (joelcarrier at gmail.com) Date: Fri, 22 Feb 2008 08:35:03 -0800 (PST) Subject: how to flush child_stdin References: <9b20c22e-db97-40bf-802a-f0f959b82c61@p43g2000hsc.googlegroups.com> <13rsmjg88a8rf45@corp.supernews.com> Message-ID: <1a5bd8fb-8aab-4aec-bf71-3802f22f3869@e25g2000prg.googlegroups.com> On Feb 22, 12:15 am, Dennis Lee Bieber wrote: > On Thu, 21 Feb 2008 12:34:28 -0800 (PST), "joelcarr... at gmail.com" > declaimed the following in comp.lang.python: > > > > > I'm opening up a subprocess like this where slave.py is a text based > > app that receives commands and responds with output: > > > r, w, e = popen2.popen3('python slave.py') > > > I need to send slave.py a command and see the output, > > so I'll do something like: > > > w.write("command here") > > then i'll try this: > > w.flush() > > > A separate thread is reading from r to retrieve output of slave.py. > > > The problem is that slave.py doesn't seem to receive commands unless I > > also do: > > w.close() > > What happens if you do: > > w.write("command here\n") > w.flush() > > Could the slave be blocked waiting for an EOL character before > processing said command? > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ I don't think that is the problem, I'm feeding it newline characters. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Feb 9 17:41:45 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 09 Feb 2008 23:41:45 +0100 Subject: OT: Star Wars and parsecs References: <28eead2f-a40c-414b-bd3d-a941f8a851a2@d70g2000hsb.googlegroups.com> <7da40f42-f64f-4939-a0dc-d24d1ff85f2d@v4g2000hsf.googlegroups.com> <13qjktdbe76da00@corp.supernews.com> <13qmp56btnr55a4@corp.supernews.com> <13qmtqebm4t6979@corp.supernews.com> <13qo0rkr7osv792@corp.supernews.com> <13qotf2mgpvkoac@corp.supernews.com> Message-ID: <616oh9F1tsk17U1@mid.individual.net> Lou Pecora wrote: [parsecs] > Which is the Earth's orbit. So, long, long ago in a galaxy far, > far away did they know about the Earth and decide to use it as the > basis for length in the universe? Even before people on earth > defined it? No, even simpler: In the Star Wars galaxy, parsec is a time unit. We on earth just accidentally defined a unit with exactly the same name -- which is a distance unit instead. :) Regards, Bj?rn -- BOFH excuse #167: excessive collisions & not enough packet ambulances From gagsl-py2 at yahoo.com.ar Tue Feb 12 12:13:09 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 12 Feb 2008 15:13:09 -0200 Subject: How to add registry on remote machine References: Message-ID: En Tue, 12 Feb 2008 14:56:09 -0200, Praveena Boppudi (c) escribi?: > Hi, > Can anyone please tell me how to add registry on remote windows machine > programmatically Using the RegConnectRegistry Windows API function http://msdn2.microsoft.com/en-us/library/ms724840.aspx From Python, you can use the pywin32 package. -- Gabriel Genellina From steve at REMOVE-THIS-cybersource.com.au Mon Feb 25 10:03:28 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 25 Feb 2008 15:03:28 -0000 Subject: How about adding rational fraction to Python? References: <13rf9tvbkt66r2a@corp.supernews.com> <198927a7-9478-42b3-a972-82049f0130ac@u10g2000prn.googlegroups.com> <1bc9bba7-dc7f-4cfe-8e1c-fa5901c9f556@n77g2000hse.googlegroups.com> <97f30679-483d-4751-9a6e-0858b36eb426@d4g2000prg.googlegroups.com> <649ac8a9-ae09-4e9b-85c2-f37043af21fd@28g2000hsw.googlegroups.com> <0d1955fc-762c-44e1-a5d8-372c71458455@p25g2000hsf.googlegroups.com> <36204e6f-0d82-449b-8ca5-c819ace9a55a@p73g2000hsd.googlegroups.com> <7xy799v7o1.fsf@ruckus.brouhaha.com> <19d08284-0682-45fc-9c45-ce917715c585@h25g2000hsf.googlegroups.com> Message-ID: <13s5m608fi1aca7@corp.supernews.com> On Sun, 24 Feb 2008 23:09:39 -0800, Carl Banks wrote: > On Feb 25, 2:04 am, Paul Rubin wrote: >> Carl Banks writes: >> > Try doing numerical integration sometime with rationals, and tell me >> > how that works out. Try calculating compound interest and storing >> > results for 1000 customers every month, and compare the size of your >> > database before and after. >> >> Usually you would round to the nearest penny before storing in the >> database. > > I throw it out there as a hypothetical, not as a real world example. > "This is why we don't (usually) use rationals for accounting." But since accountants (usually) round to the nearest cent, accounting is a *good* use-case for rationals. Decimal might be better, but floats are worst. I wonder why you were doing numerical integration with rationals in the first place? Are you one of those ABC users (like Guido) who have learnt to fear rationals because ABC didn't have floats? -- Steven From steve at holdenweb.com Sat Feb 23 08:16:44 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 23 Feb 2008 08:16:44 -0500 Subject: Globals or objects? In-Reply-To: <13rupr7e13r98e0@corp.supernews.com> References: <72b59db8-ec9c-480a-9ae7-92a69acb70a6@41g2000hsc.googlegroups.com> <47bd7ffe$0$514$bed64819@news.gradwell.net> <47bda8e4$0$515$bed64819@news.gradwell.net> <13rrv057bt35o18@corp.supernews.com> <47beb990$0$513$bed64819@news.gradwell.net> <13rtpvuoo1uea8d@corp.supernews.com> <47bf1a42$0$513$bed64819@news.gradwell.net> <13rupr7e13r98e0@corp.supernews.com> Message-ID: <47C01CBC.40108@holdenweb.com> Steven D'Aprano wrote: > On Fri, 22 Feb 2008 18:53:54 +0000, tinnews wrote: > >>>> But you're not comparing what the OP posted. He was comparing a >>>> global with an object with a single variable inside it. Either would >>>> work with the y = spam(arg) example above. >>> What do you mean by "an object with a single variable inside it"? I >>> don't understand what that is supposed to mean, or why you think it is >>> the same as a global. Do you mean a Singleton? >>> >>> If so, then the answer is simple: using a Singleton argument instead of >>> a global is better, because with a global you are stuck to always using >>> the global (at least until you can re-write the code), but with the >>> Singleton argument, you may be enlightened and *not* use a Singleton. >>> >> But if you stop using the Singleton the code no longer does the same as >> it would with a global does it? > > That's a *good* thing, not a problem. The whole idea is to get away from > the bad behaviour of globals, not find some other way to implement it. > I think that advocation of a global singleton is not really solving the problem. Not the problem I perceive, anyway. From your comments it's difficult to see whether we share the same perceptions, so let me elucidate. The issue I have with globals is primarily that use of a global introduces a tight coupling between a function and its environment, since any environment that uses the function has to provide the global. It's true that a global singleton is a half-way step to a solution of the problem because it portends the true solution, which also solves the problem of multiple counts. That solution, of course, is to have the "function" become a method of some counter object, which can then be used to count many things. In other words (untested, so ignore the many Holden types that this will inevitably incur): -------- bad.py: counter = 0 def count(n): global counter counter += n -------- justasbadifnotworse.py: class bunch: pass; counter = bunch() bunch.count = 0 def count(n): counter.count += n -------- better.py: class Counter: def __init__(self): self.count = 0 counter1 = Counter() counter2 = Counter() def count(n, counter): counter.count += n -------- best.py: class Counter: def __init__(self): self.count = 0 def count(self, n): self.count += n -------- Now the names I have chosen are pejorative, but this is typically the development you see in someone's programming style as they slowly (or not slowly) start to understand the value of the object-oriented approach. Unfortunately this sometimes goes too far, and people end up writing "monster objects", with dozens of methods and lots of instance variables used to communicate between them. With that style of programming the instance variables introduce the same tight coupling between the methods that globals do in a less object-oriented style, and the code becomes just as difficult to understand. Only now there can be multiple instances of the badly-written function! Sometimes this is inevitable, but good programming style is about trying to strike the right balance between contexts. It is truly possible to write good and bad programs in any language you like, and rules like "globals are bad" need to be taken in context just like any other rule. After all, some things *have* to be global for our programs to make any sense at all, unless you want to adopt a truly functional style that has never appealed to me. I like my programs to have state. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From duncan.booth at invalid.invalid Tue Feb 19 09:28:39 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 Feb 2008 14:28:39 GMT Subject: Call for volunteers to help maintain bugs.python.org's issue tracker References: <7xir0lm44r.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Brett Cannon" writes: >> The Python Software Foundation's infrastructure committee is looking >> for volunteers to help maintain the Roundup issue tracker installed >> for http://bugs.python.org. Responsibilities revolve around >> maintaining the Roundup installation itself (tracker schema, modifying >> the installed copy of Roundup, etc.) and the occasional database work >> (changes to the database, etc.). > > Didn't Python.org choose the proprietary Roundup system over a free > bug tracker precisely to avoid having to do that kind of maintainance? > Ok, I'll bite. In what way is Roundup proprietary? So far as I can tell it has a very unrestrictive license: maintain the copyright notice and otherwise do what you want, except for the parts derived from Zope which use the ZPL v2.0. From asdfsdf at asd.com Tue Feb 26 10:45:10 2008 From: asdfsdf at asd.com (saneman) Date: Tue, 26 Feb 2008 16:45:10 +0100 Subject: Break lines? Message-ID: I have made this string: TITLE = 'Efficiency of set operations: sort model, (cphstl::set::insert(p,e)^n cphstl::set::insert(e)), integer' But I am not allowed to break the line like that: IndentationError: unexpected indent How do I break a line? From jeffober at gmail.com Tue Feb 5 13:20:20 2008 From: jeffober at gmail.com (Jeff) Date: Tue, 5 Feb 2008 10:20:20 -0800 (PST) Subject: Why not a Python compiler? References: <28eead2f-a40c-414b-bd3d-a941f8a851a2@d70g2000hsb.googlegroups.com> Message-ID: <0208d0bb-c4b5-4a31-9518-b25cb1a07cc6@f10g2000hsf.googlegroups.com> I'm surprised no one has mentioned Pyrex. It can be used to write stand-alone C programs using near-Python syntax: Pyrex: http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/ Stand-alone how-to: http://www.freenet.org.nz/python/embeddingpyrex/ Pyrex how-to: http://ldots.org/pyrex-guide/, http://www.artfulcode.net/articles/extending-python-pyrex/ (shameless plug, I know) From bbxx789_05ss at yahoo.com Tue Feb 19 03:42:37 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Tue, 19 Feb 2008 00:42:37 -0800 (PST) Subject: usage of .encode('utf-8','xmlcharrefreplace')? References: <797aa70a-d876-4f61-b3bd-332429cd7661@i12g2000prf.googlegroups.com> Message-ID: <053c2df3-db9d-4f41-9525-58db0a12d492@q78g2000hsh.googlegroups.com> On Feb 19, 12:15?am, J Peyret wrote: > On Feb 18, 10:54 pm, 7stud wrote: > > > One last point: you can't display a unicode string. ?The very act of > > trying to print a unicode string causes it to be converted to a > > regular string. ?If you try to display a unicode string without > > explicitly encode()'ing it first, i.e. converting it to a regular > > string using a specified secret code--a so called 'codec', python will > > implicitly attempt to convert the unicode string to a regular string > > using the default codec, which is usually set to ascii. > > Yes, the string above was obtained by printing, which got it into > ASCII format, as you picked up. > Something else to watch out for when posting unicode issues. > > The solution I ended up with was > > 1) Find out the encoding in the data file. > > In Ubuntu's gedit editor, menu 'Save As...' displays the encoding at > the bottom of the save prompt dialog. > > ISO-8859-15 in my case. > > 2) Look up encoding corresponding to ISO-8859-15 at > > http://docs.python.org/lib/standard-encodings.html > > 3) Applying the decode/encode recipe suggested previously, for which I > do understand the reason now. > > #converting rawdescr > #from ISO-8859-15 (from the file) > #to UTF-8 (what postgresql wants) > #no error handler required. > decodeddescr = rawdescr.decode('iso8859_15').encode('utf-8') > > postgresql insert is done using decodeddescr variable. > > Postgresql is happy, I'm happy. Or, you can cheat. If you are reading from a file, you can make set it up so any string that you read from the file automatically gets converted from its encoding to another encoding. You don't even have to be aware of the fact that a regular string has to be converted into a unicode string before it can be converted to a regular string with a different encoding. Check out the codecs module and the EncodedFile() function: import codecs s = 'he Company\xef\xbf\xbds ticker' f = open('data2.txt', 'w') f.write(s) f.close() f = open('data2.txt') f_special = codecs.EncodedFile(f, 'utf-8', 'iso8859_15') #file, new encoding, file's encoding print f_special.read() #If your display device understands utf-8, you will see the troublesome character displayed. #Are you sure that character is legitimate? f.close() f_special.close() From gagsl-py2 at yahoo.com.ar Wed Feb 27 15:11:32 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 27 Feb 2008 18:11:32 -0200 Subject: Making string-formatting smarter by handling generators? References: <47C58E95.1030000@tim.thechases.com> Message-ID: En Wed, 27 Feb 2008 14:23:49 -0200, Tim Chase escribi?: > Is there an easy way to make string-formatting smart enough to > gracefully handle iterators/generators? E.g. > > transform = lambda s: s.upper() > pair = ('hello', 'world') > print "%s, %s" % pair # works > print "%s, %s" % map(transform, pair) # fails > > with a """ > TypeError: not enough arguments for format string > """ Note that your problem has nothing to do with map itself. String interpolation using % requires either many individual arguments, or a single *tuple* argument. A list is printed as itself. py> "%s, %s" % ['hello', 'world'] Traceback (most recent call last): File "", line 1, in TypeError: not enough arguments for format string py> "%s" % ['hello', 'world'] "['hello', 'world']" So the answer is always use tuple(...) as others pointed. -- Gabriel Genellina From bearophileHUGS at lycos.com Thu Feb 7 03:20:52 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 7 Feb 2008 00:20:52 -0800 (PST) Subject: Why does list have no 'get' method? References: <95d6e98c0802060253gde6233cn97d42c344b382416@mail.gmail.com> <7xzlud9sof.fsf@ruckus.brouhaha.com> Message-ID: <36d4dbb4-bf0a-4a1a-8c93-f6636434fd0b@v67g2000hse.googlegroups.com> Paul Rubin: > I like the suggestion, except it should be > port = int(sys.argv.get(1, '8000')) > one could imagine your example going wrong in a protocol where 0 is > a valid port number. I think a high-level language like Python must have boolean operators (or and not) that behave in a much more clean way, with a simpler semantics. That is they have to return only true or false. Otherwise they are just a source of bugs and confusion. This is a change fit for Python 3. That trick with or/and may look good for Perl, but it's unfit for a language that tries to be clear, readable from people that don't know it much, and good to learn to program. Python has now the if-then expression too that is more clear. Bye, bearophile From gherron at islandtraining.com Sun Feb 24 11:18:33 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 24 Feb 2008 08:18:33 -0800 Subject: simpleparse - what is wrong with my grammar? In-Reply-To: <47C13D9E.9060908@shopzeus.com> References: <47C13D9E.9060908@shopzeus.com> Message-ID: <47C198D9.9040405@islandtraining.com> Laszlo Nagy wrote: > The program below gives me "segmentation fault (core dumped)". > > Environment: > Linux gandalf-desktop 2.6.20-16-generic #2 SMP Tue Feb 12 05:41:34 > UTC 2008 i686 GNU/Linux > Python 2.5.1 > > What is wrong with my grammar? Can it be an internal error in simpleparse? > There's no way to tell from here. It's almost certainly a problem with simpleparse. Can you contact the developers of simpleparse? There is more you can do on your own: Use a debugger or prints to decide which python line is causing this. (Almost certainly the parse.parse, but *make sure* of that ...) Then start reducing your grammar bit-by-bit until you get a working grammar and so narrow in on the portion that's causing this problem. This way, you may answer your own question, or provide enough information to motivate any knowledgeable volunteers to actually volunteer their time. Good luck. Gary Herron > Thanks, > > Laszlo > > > from simpleparse.common import numbers, strings, comments > from simpleparse.parser import Parser > > declaration = r''' > expr := paren_expr/unop_expr/binop_expr/word > paren_expr := "(",expr,")" > unop_expr := unop,expr > binop_expr := expr,binop,expr > unop := ("+"/"-") > binop := ("|"/"&"/"@") > word := [a-zA-Z], [a-zA-Z0-9_]* > ''' > > parser = Parser( declaration) > success, resultTrees, nextCharacter = > parser.parse("testword",production="expr",processor=None) > print success > > > From castironpi at gmail.com Thu Feb 14 13:11:48 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 14 Feb 2008 10:11:48 -0800 (PST) Subject: XML pickle References: <686a4012-1c9e-456e-973c-c1e396f4c060@s8g2000prg.googlegroups.com> <47B3E3A3.1070205@behnel.de> Message-ID: On Feb 14, 12:45?am, Stefan Behnel wrote: > Hi, > > castiro... at gmail.com wrote: > > Readability of the Pickle module. ?Can one export to XML, from cost of > > speed and size, to benefit of user-readability? > > Regarding pickling to XML, lxml.objectify can do that: > > http://codespeak.net/lxml/objectify.html > > however: > > > It does something else: plus functions do not export their code, > > either in interpreter instructions, or source, or anything else; and > > classes do not export their dictionaries, just their names. ?But it > > does export in ASCII. > > > Pickle checks any __safe_for_unpickling__ and __setstate__ methods, > > which enable a little encapsulating, but don't go far. > > I'm having a hard time to understand what you are trying to achieve. Could you > state that in a few words? That's usually better than asking for a way to do X > with Y. Y (i.e. pickling in this case) might not be the right solution for you. > > Stefan The example isn't so bad. It's not clear that it isn't already too specific. Pickling isn't what I want. XML is persistent too. XML could go a couple ways. You could export source, byte code, and type objects. (Pickle could do that too, thence the confusion originally.) gnosis.xml and lxml have slightly different outputs. What I'm going for has been approached a few different times a few different ways already. If all I want is an Excel-readable file, that's one end of the spectrum. If you want something more general, but still include Excel, that's one of many decisions to make. Ideas. How does lxml export: b= B(); a.b= b; dumps( a )? It looks like he can create the XML from the objects already. From steve at holdenweb.com Fri Feb 29 10:35:29 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 29 Feb 2008 10:35:29 -0500 Subject: joining strings question In-Reply-To: <6b41eaf1-05e1-4b04-8c31-6737166f267f@b1g2000hsg.googlegroups.com> References: <6b41eaf1-05e1-4b04-8c31-6737166f267f@b1g2000hsg.googlegroups.com> Message-ID: patrick.waldo at gmail.com wrote: > Hi all, > > I have some data with some categories, titles, subtitles, and a link > to their pdf and I need to join the title and the subtitle for every > file and divide them into their separate groups. > > So the data comes in like this: > > data = ['RULES', 'title','subtitle','pdf', > 'title1','subtitle1','pdf1','NOTICES','title2','subtitle2','pdf','title3','subtitle3','pdf'] > > What I'd like to see is this: > > [RULES', 'title subtitle','pdf', 'title1 subtitle1','pdf1'], > ['NOTICES','title2 subtitle2','pdf','title3 subtitle3','pdf'], etc... > > I've racked my brain for a while about this and I can't seem to figure > it out. Any ideas would be much appreciated. > > Thanks data = ['RULES', 'title','subtitle','pdf', 'title1','subtitle1','pdf1','NOTICES','title2','subtitle2','pdf','title3','subtitle3','pdf'] olist = [] while data: if data[0] == data[0].upper(): olist.append([data[0]]) del data[0] else: olist[-1].append(data[0]+' '+data[1]) olist[-1].append(data[2]) del data[:3] print olist However, I suspect you should be asking yourself whether this is really an appropriate data structure for your needs. If you say what you are trying to achieve in the large rather than focusing on a limited programming issue there may be much better solutions. I suspect, for example, that a dict indexed by the categories and with the entries each containing a list of tuples might suit your needs much better, i.e. { 'RULES': [('title subtitle', 'pdf'), ('title1 subtitle1', 'pdf')], 'NOTICES': [('title2 subtitle2', 'pdf'), 'title3 subtitle3', 'pdf')]} One final observation: if all the files are PDFs then you might just as well throw the 'pdf' strings away and use a constant extension when you try and open them or whatever :-). Then the lists of tuples i the dict example could just become lists of strings. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From carsten at uniqsys.com Wed Feb 13 13:53:00 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 13 Feb 2008 13:53:00 -0500 Subject: Regular Expression for Prime Numbers (or How I came to fail at them, and love the bomb) In-Reply-To: References: <85ca4615-c51f-4aab-b400-f3f80056faec@l32g2000hse.googlegroups.com> Message-ID: <1202928780.12316.10.camel@dot.uniqsys.com> On Wed, 2008-02-13 at 10:40 -0800, mensanator at aol.com wrote: > But why doesn't it work when you make that change? I can't answer that question, because it *does* work when you make that change. -- Carsten Haese http://informixdb.sourceforge.net From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Feb 22 04:11:23 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 22 Feb 2008 10:11:23 +0100 Subject: Article of interest: Python pros/cons for the enterprise In-Reply-To: <0KmdnT0LF9KUICDanZ2dnUVZ_qygnZ2d@comcast.com> References: <2f1527a7-2f66-44c7-9665-4d8ff01fa5ab@28g2000hsw.googlegroups.com> <47bd4a24$0$25225$426a74cc@news.free.fr> <0KmdnT0LF9KUICDanZ2dnUVZ_qygnZ2d@comcast.com> Message-ID: <47be9150$0$22249$426a74cc@news.free.fr> Jeff Schwab a ?crit : > Bruno Desthuilliers wrote: >> Carl Banks a ?crit : >>> On Feb 20, 8:58 am, Tim Chase wrote: >>>>> You Used Python to Write WHAT? >>>>> http://www.cio.com/article/185350 >>>> """ >>>> Furthermore, the power and expressivity that Python offers means >>>> that it may require more skilled developers. >>>> [...down to the summary...] >>>> Python may not be an appropriate choice if you: >>>> [...] >>>> * Rely on teams of less-experienced programmers. These >>>> developers may benefit from the wider availability of training >>>> for languages like Java and are less likely to make mistakes with >>>> a compile-time, type-checked language. >>>> """ >>>> >> (snip) >>> >>> C++ is a compile-time, type-checked language, which means it is >>> totally safer for newbies than Python. Yep, your big company is >>> totally safe with newbie C++ programmers. >>> >> >> Mouarf ! Brillant demonstration, thanks Carl !-) >> >> (and BTW, +1 QOTW) > > > NB: This is not a troll. (Please, nobody try to be cute with a "yes it > is" reply.) NB : standard disclaimer about all the following being MVHO. > c.l.python seem to be about the most close-minded of any of the > currently popular language-specific news groups. May I suggest you take a tour on c.l.lisp then ?-) > It's just taken for > granted that Perl and C++, two of my personal favorite things in this > world, inherently favor ugly, buggy code. I wouldn't say so. It's a fact that C++ is a really complex language with quite a lot of room for BigMistakes(tm), and that there's something like a 'my-code-is-more-cryptic-than-yours' culture in Perl. You cannot seriously argue on this. Now this has nothing to do with the respective merits of both languages (FWIW, Perl, as a 'Practical Extracting and Reporting Language', beats any other language I know pants down), and I'd be sorry if you were to confuse what is mostly on the friendly jokes side with mere bashing. You may not have noticed, but quite a lot of people here have a working experience with either C++ and/or Perl. As for my above comment, it doesn't imply anything else than the fact that C++ is way harder to learn than Python (or Ruby etc...), and that bugs in C++ code are likely to have way more nasty results. The joke is not "against" C++, but about people asserting than static type checking is safer than dynamic type checking without realizing that what is really important is*runtime type checking - something C++ doesn't provide. NB : As a side note, and while being myself a bit passionated when it comes to languages and my job in general, I would not go as far as labelling any language or technology as "one of my favorite things in this world". > That is the farthest thing > from the truth as I see it. You can (and plenty of people will) write > terrible code in any language, including Python. Indeed. Bad coders write bad code, period. And I think we've all been bad coders one day, and that we're all still bad coders sometimes. > To use Python effectively, you have to know something about how it > works, and the same is true of Perl and C++. And of any other language. Now a decent C++ or Perl programmer can be proficient in Python in a couple weeks and become a master within a year at worst. And it seems that non-professional, occasional programmers (hobbyists, gamers, scientists, and any other kind of power user) are able to get their job done in Python without much pain. > But a newbie who's > learning from a decent source (avoid the "C++ for Morons" style books) > is likely (I contend) to be writing semi-useful programs about as fast > as with Python, and to be writing heavy-duty work-horse programs far > sooner. Sorry but I don't buy this. > Perl is, and always has been, a language for getting your job done; when > everything else failed, Perl and C++ got me through some of the toughest > tasks of my life. Translating file formats, automating system-level > tasks... And now that the C++ standard library is getting regular > expressions, I can replace plenty of glued-together scripts with > single-language, cohesive applications. > > I like Python, and I think it's got a brilliant future ahead of it. It > is rapidly becoming the dynamic language of choice, especially for C++ > projects. I am glad that Python can be extended straightforwardly in > any C-linkable language. But this bashing of other powerful languages > on the basis that they're hard to read and hard to use correctly is, > frankly, nonsense. Stating the obvious is not bashing. In my last shop I was working with (very talented BTW) Perl programmer, and he was the first to make jokes on Perl's abuse of cryptic syntax. From castironpi at gmail.com Fri Feb 15 12:10:42 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 15 Feb 2008 09:10:42 -0800 (PST) Subject: XML pickle References: <686a4012-1c9e-456e-973c-c1e396f4c060@s8g2000prg.googlegroups.com> <47B3E3A3.1070205@behnel.de> <47B488FD.1090502@behnel.de> <47B49B3E.3060609@behnel.de> <47B553EF.5080605@behnel.de> Message-ID: > > Can you use set( '{ss}Type' ) somehow? > > What is 'ss' here? A prefix? > > What about actually reading the tutorial? > > http://codespeak.net/lxml/tutorial.html#namespaces > > > And any way to make this look > > closer to the original? > > What's the difference you experience? Target: abc 123
It helped get me the working one, actually-- the tutorial. 'ss' is, and I don't know the jargon for it, a local variable, or namespace variable, prefix?, or something. xmlns:ss="urn:schemas-microsoft- com:office:spreadsheet". The ElementMaker example is closest, I think, but it's working, so, ... I'm more interested in a simplification of the construction code, and at this point I can get goofy and brainstorm. Ideas? From paul.hankin at gmail.com Fri Feb 8 12:06:22 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Fri, 8 Feb 2008 09:06:22 -0800 (PST) Subject: are elements of a list in sequence in list b References: Message-ID: <8e81e898-e75e-434e-bef9-3cdcac31694e@d21g2000prf.googlegroups.com> Matthew_WAR... at bnpparibas.com wrote: > I need to search list a for the sequence of list b def list_contains(a, b): return any(a[i:i+len(b)] == b for i in range(len(a) - len(b) + 1)) list_contains(range(1, 7), [2, 3, 4]) -- Paul Hankin From bj_666 at gmx.net Fri Feb 22 11:13:50 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 22 Feb 2008 16:13:50 GMT Subject: Article of interest: Python pros/cons for the enterprise References: <2f1527a7-2f66-44c7-9665-4d8ff01fa5ab@28g2000hsw.googlegroups.com> <47bd4a24$0$25225$426a74cc@news.free.fr> <036e93e6-5840-4a3c-8642-67a0a9ec44f2@i7g2000prf.googlegroups.com> <784ec210-f389-4a15-b458-961100de9103@v3g2000hsc.googlegroups.com> <9a3f9e3c-acf5-453f-a075-e0a044b21237@p73g2000hsd.googlegroups.com> <7xwsoxdzb8.fsf@ruckus.brouhaha.com> Message-ID: <628aluF21f45aU5@mid.uni-berlin.de> On Fri, 22 Feb 2008 04:48:28 -0800, Nicola Musatti wrote: > On Feb 22, 12:07 pm, Paul Rubin wrote: >> Nicola Musatti writes: >> > In C++ memory is just another resource which you can handle just like >> > any other one, possibly using RAII. >> >> Ok, I'll bite. Here's a straightforward Python expression: >> >> a = [f(x) + g(y) for x,y in izip(m1, m2) if h(x,y).frob() == 7] >> >> Consider how many intermediate objects are being allocated in figuring >> out that listcomp. Do you REALLY want to manage all the deallocation >> with something like RAII? > > > What makes you think that a translation of a similar expression would > involve explicit dynamic allocation at all? Barring bugs, here's an > equivalent example: > > #include > #include > #include > > int f(int n) { return n * 2; } > int g(int n) { return ( n * 2 ) + 1; } > > std::map izip(int i, int j) { > std::map m; > m[i] = j; > m[j] = i; > return m; > } > > class A { > int i, j; > public: > A(int ii, int jj) : i(ii), j(jj) {} > int frob() { return i + j; } > }; > > A h(int i, int j) { return A(i, j); } > > int main() { > int m1 = 3; > int m2 = 4; > std::vector a; > std::map m = izip(m1, m2); > for ( std::map::iterator i = m.begin(); i != m.end(); ++i ) > { > if ( h(i->first, i->second).frob() == 7 ) > a.push_back(f(i->first) + g(i->second)); > } > for ( std::vector::iterator i = a.begin(); i != a.end(); ++i ) > std::cout << *i << '\n'; > } > > As you can see the standard library takes care of all memory > management. Aaah, that's much nicer and easier to understand than the list comprehension. After this great example I'll switch to C++. ;-) But somehow you still manage memory by writing in a style that favors value types. SCNR, Marc 'BlackJack' Rintsch From bignose+hates-spam at benfinney.id.au Fri Feb 8 20:02:24 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 09 Feb 2008 12:02:24 +1100 Subject: __builtins__ References: <612lj5F1tbd9kU1@mid.uni-berlin.de> <47ac380f$0$23597$426a74cc@news.free.fr> Message-ID: <87myqb7xi7.fsf@benfinney.id.au> LHB writes: > Marc 'BlackJack' Rintsch a ?crit : > > `__builtins__` is an implementation detail, and `__builtin__` is a name > > of a module you can import. You should not use `__builtins__` but import > > `__builtin__` and inspect that instead of `__builtins__`. > Ok. Should I only see `__builtins__` as an access to builtin > functions/exception/... ? No, if you want that access, explicitly 'import __builtin__' and access them that way. Ignore '__builtins__' altogether as an implementation detail. (This is difficult to adhere to because the names are confusingly similar; this is an acknowledged wart in current Python.) IIRC this behaviour will change in Python 3.0, where 'import __builtin__' will be the *only* way to get at builtins from normal code. At least, I'm now writing my code as though that's the case :-) -- \ ?The man who is denied the opportunity of taking decisions of | `\ importance begins to regard as important the decisions he is | _o__) allowed to take.? ?C. Northcote Parkinson | Ben Finney From http Fri Feb 8 04:18:11 2008 From: http (Paul Rubin) Date: 08 Feb 2008 01:18:11 -0800 Subject: Pure Python Salsa20 Stream Cipher Implementation References: <6ddc44aa-7c71-4cee-a6db-31dac0402bd6@z17g2000hsg.googlegroups.com> Message-ID: <7xmyqbvmb0.fsf@ruckus.brouhaha.com> betabrain.honshu at gmail.com writes: > for those of you who are familiar with the micropledge.com project, > here is a good opportunity to spend or earn something: > http://micropledge.com/projects/pysalsa20 I don't understand why a pure python version of salsa20 would be interesting. Is there some application that uses salsa20, that's worth being able to interoperate with in pure python? If you just want a stream cipher in pure python (including its standard library), the fastest way seems to be able to use the sha module as a building block: http://www.nightsong.com/phr/crypto/p3.py From deets at nospam.web.de Sat Feb 9 14:10:54 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 09 Feb 2008 20:10:54 +0100 Subject: dependency order In-Reply-To: References: Message-ID: <616c6fF1tp0qnU1@mid.uni-berlin.de> belred at gmail.com schrieb: > i'm having trouble trying to figure this out... it's part of a build > system i'm writing in python. maybe someone has a good simple way to > solve this. i'm trying to create a dependency order out of multiple > lists. > > list1: B C > list2: A B > list3: A C > > i want the end result to be the list: A B C > i'm very frustrated that i can't come up with anything that always > works. > > > thanks... any clues to solve this would be greatly appreciated. Maybe the frustration is based on the IMHO wrong data-structure you use. What does [B, C] mean? A common approach for this is to create a dict instead, that maps an object to the list of things it depends on (or that depend on it, it's essentially the same) The resulting data-structure is called a directed graph, and there are algorithms like "partial orderings" you can google for that will help you. An example graph would be: dict( "A" : ["B", "C"], "B" : ["C"] "C" : [] ) Then the result of a partial ordering would be ["C", "B", "A"] which should be what you are after. Diez From bbxx789_05ss at yahoo.com Wed Feb 27 08:50:35 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Wed, 27 Feb 2008 05:50:35 -0800 (PST) Subject: BaseHTTPServer and do_POST method References: <0215927e-0d35-4b97-b5b1-bc46cd6f3b88@64g2000hsw.googlegroups.com> Message-ID: <2fdc85df-f830-45db-a313-87f4d89c1803@h11g2000prf.googlegroups.com> On Feb 27, 5:33?am, rocksportrocker wrote: > Hi, > > I am trying to implement a local server for storing and retrieving > numerical data. > So I use BaseHTTPServer as follows: > > --------------------------------------------------------- > ? ? from BaseHTTPServer import * > > ? ? class Handler(BaseHTTPRequestHandler): > > ? ? ? ? def do_POST(self): > > ? ? ? ? ? ? print "POST" > ? ? ? ? ? ? self.send_response(200) > > ? ? httpd = HTTPServer(("",8000), Handler) > ? ? httpd.serve_forever() > --------------------------------------------------------- > > For testing I use: > > --------------------------------------------------------- > > ? ? import httplib > > ? ? data = "123456789o" * 100 > > ? ? conn = httplib.HTTPConnection("localhost:8000") > ? ? print conn.request("POST", "/", data) > > --------------------------------------------------------------- > > Executing this client, the server says: > > ? ? error(10053, 'Software caused connection abort') > > If I add "conn.getresponse()" at the end of the test script, the > message disapears, but the server hangs. > > Where is my mistake ? > > Greetings, Uwe. I don't get that error. On the server, I get the output: POST localhost - - [27/Feb/2008 06:49:13] "POST / HTTP/1.1" 200 - and on the client I get: None I don't know what's causing the second line of output on the server. From Robert.Bossy at jouy.inra.fr Mon Feb 11 11:48:14 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Mon, 11 Feb 2008 17:48:14 +0100 Subject: OT: Speed of light [was Re: Why not a Python compiler?] In-Reply-To: <13r0si76tvs8o90@corp.supernews.com> References: <28eead2f-a40c-414b-bd3d-a941f8a851a2@d70g2000hsb.googlegroups.com> <7da40f42-f64f-4939-a0dc-d24d1ff85f2d@v4g2000hsf.googlegroups.com> <13qjktdbe76da00@corp.supernews.com> <13qkhka8rln51c5@corp.supernews.com> <47adb0ca$0$31274$e4fe514c@dreader27.news.xs4all.nl> <13qs32es4eaj335@corp.supernews.com> <61aa39F1tt6irU1@mid.individual.net> <13r0si76tvs8o90@corp.supernews.com> Message-ID: <47B07C4E.90608@jouy.inra.fr> Grant Edwards wrote: > On 2008-02-11, Steve Holden wrote: > > >> Well the history of physics for at least two hundred years has >> been a migration away from the intuitive. >> > > Starting at least as far back as Newtonian mechanics. I once > read a very interesting article about some experiments that > showed that even simple newtonian physics is counter-intuitive. > Two of the experiments I remember vividly. One of them showed > that the human brain expects objects constrained to travel in a > curved path will continue to travel in a curved path when > released. The other showed that the human brain expects that > when an object is dropped it will land on a spot immediately > below the drop point -- regardless of whether or not the ojbect > was in motion horizontally when released. > > After repeated attempts at the tasks set for them in the > experiments, the subjects would learn strategies that would > work in a Newtonian world, but the initial intuitive reactions > were very non-Newtonian (regardless of how educated they were > in physics). > I'm pretty sure we can still hear educated people say that free fall speed depends on the weight of the object without realizing it's a double mistake. Cheers, RB From kw at codebykevin.com Mon Feb 4 11:46:58 2008 From: kw at codebykevin.com (Kevin Walzer) Date: Mon, 04 Feb 2008 11:46:58 -0500 Subject: Python GUI toolkit In-Reply-To: References: <42c7d139-3520-4d73-85cd-f67e3bdacd5a@c4g2000hsg.googlegroups.com> <47A735D0.9000902@codebykevin.com> Message-ID: <47A74182.7020306@codebykevin.com> Chris Mellon wrote: > > I didn't say inherently unable, I said the toolkit doesn't provide it. > Note that you said that you did a lot of work to follow OS X > conventions and implement behavior. The toolkit doesn't help you with > any of this. A mac-native toolkit (or one that strives for native > behavior, like wxPython) eliminates a lot of this work (although, of > course, not all). If the toolkit doesn't provide it, then I think that means "inherently unable." On the Mac, Tk provides a mechanism that allows hooking up arbitrary events to arbitrary keyboard. Something like: self.bind('', lambda event: self.authorizeCommand(self.installPackage)) I have to specify the key-combination--that's all. One line of code. No implementing of keyboard bindings in C or at the Tcl/Tk or even Python-Tkinter level--it's all already defined by the toolkit. By contrast, Cocoa/Objective-C has a rather complex system for defining keyboard events: http://developer.apple.com/documentation/Cocoa/Conceptual/EventOverview/HandlingKeyEvents/chapter_6_section_1.html#//apple_ref/doc/uid/10000060i-CH7-SW1 PyObjC is a thin wrapper over Objective-C, so you'd have to do the equivalent calls in Python to implement custom keyboard behavior. It is true that Cocoa some convenience methods in Interface Builder, i.e. common menu commands don't require any extra code: if you are developing a document-based application, "Command-C" is implemented in the menu and in the frameworks as "copy (text, image, whatever) to clipboard." But "Command-C" also works identically in the Tk console. Tk does lack some things. It doesn't support drag-and-drop on the Mac. It doesn't hook into some of the newer Mac visual styles. Getting access to this would require an extension or patching Tk's core. In those events, I emulate the behavior or appeareance, which Tk makes very easy. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From nicola.musatti at gmail.com Thu Feb 21 10:11:28 2008 From: nicola.musatti at gmail.com (Nicola Musatti) Date: Thu, 21 Feb 2008 16:11:28 +0100 Subject: Article of interest: Python pros/cons for the enterprise In-Reply-To: <47BD921F.4050505@tim.thechases.com> References: <2f1527a7-2f66-44c7-9665-4d8ff01fa5ab@28g2000hsw.googlegroups.com> <47bd4a24$0$25225$426a74cc@news.free.fr> <47BD921F.4050505@tim.thechases.com> Message-ID: Please do not reply personally to newsgroup postings, thank you. On Thu, Feb 21, 2008 at 4:00 PM, Tim Chase wrote: [...] -- Nicola.Musatti gmail com Home: http://nicola.musatti.googlepages.com/home Blog: http://wthwdik.wordpress.com/ From BjornSteinarFjeldPettersen at gmail.com Sat Feb 9 22:35:35 2008 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Sat, 9 Feb 2008 19:35:35 -0800 (PST) Subject: Is there an easy way to sort a list by two criteria? References: <902c5105-c85d-4ba5-8c9f-0dd5061cef9e@b2g2000hsg.googlegroups.com> Message-ID: <492e8201-13d6-40d9-b8ba-23f7af781946@m34g2000hsb.googlegroups.com> On Feb 10, 3:05 am, neocortex wrote: > Hello! > I am a newbie in Python. Recently, I get stuck with the problem of > sorting by two criteria. In brief, I have a two-dimensional list (for > a table or a matrix). Now, I need to sort by two columns, but I cannot > figure out how to do that. I read somewhere that it is possible to do:>>> table.sort().sort() > > but it does not work. > Can anyone help me with this? > PS: I am using Python under Ubuntu 6.06. > > Best, > PM I'm not sure which Python is default for Ubuntu 6.06, but assuming you can access a recent one (2.4), the list.sort() function takes a key argument (that seems to be rather sparsely documented in the tutorial and the docstring...). E.g.: >>> lst = [(1,2,4),(3,2,1),(2,2,2),(2,1,4),(2,4,1)] >>> lst.sort(key=lambda (a,b,c):(c,b)) >>> lst [(3, 2, 1), (2, 4, 1), (2, 2, 2), (2, 1, 4), (1, 2, 4)] >>> The "fancy" lambda simply takes a source-tuple and returns a tuple of the keys to be sorted on, in this case sort on the last element, then on the middle element. You can use the cmp argument to get similar results (with the same list as above): >>> lst.sort(cmp=lambda (a1,a2,a3),(b1,b2,b3):cmp((a3,a2),(b3,b2))) >>> lst [(3, 2, 1), (2, 4, 1), (2, 2, 2), (2, 1, 4), (1, 2, 4)] The lambda in this case is starting to get complicated though, so probably better to write a separate function. Using the cmp argument is slower than using the key argument since key is only called once for each element in the list while cmp is called for each comparison of elements (it's not the number of times the function is called that's the big deal, but rather that the highly optimized sort needs to continually call back to Python in the cmp case). The old-school way of doing this is using a Schwartzian transform (a.k.a. decorate-sort-undecorate) which creates an auxilliary list with the keys in correct sorting order so that sort() can work directly: >>> lst [(1, 2, 4), (3, 2, 1), (2, 2, 2), (2, 1, 4), (2, 4, 1)] >>> decorate = [(x[2],x[1],x) for x in lst] >>> decorate.sort() >>> decorate [(1, 2, (3, 2, 1)), (1, 4, (2, 4, 1)), (2, 2, (2, 2, 2)), (4, 1, (2, 1, 4)), (4, 2, (1, 2, 4))] >>> lst = [x[2] for x in decorate] # undecorate >>> lst [(3, 2, 1), (2, 4, 1), (2, 2, 2), (2, 1, 4), (1, 2, 4)] >>> hth, -- bjorn From olaf_schwarz_hh at yahoo.de Sun Feb 24 10:39:23 2008 From: olaf_schwarz_hh at yahoo.de (Olaf Schwarz) Date: Sun, 24 Feb 2008 07:39:23 -0800 (PST) Subject: _struct in Python 2.5.2 Message-ID: Hi, I am trying to run this application http://svn.navi.cx/misc/trunk/python/bemused/ on uNSLUng Linux 6.10 using the optware python packages. As I obtained segmentation faults using Python 2.4, I have upgraded to 2.5.2. Now the execution terminates a lot earlier with this error message: File "/usr/local/bemused_mpd/bemused-mpd.py", line 33, in import bemused File "/usr/local/bemused_mpd/bemused.py", line 27, in import bluetooth, syslog File "/opt/lib/python2.5/site-packages/bluetooth.py", line 2, in import struct File "/opt/lib/python2.5/struct.py", line 30, in from _struct import Struct, error ImportError: No module named _struct I found out that there has been a file named _struct.so in 2.5.1 but it has disappeared in 2.5.2. With no package available for downgrading to 2.5.1 and no idea how to resolve this I am stuck at this point. Any help appreciated. Thank you Olaf From Robert.Bossy at jouy.inra.fr Fri Feb 29 09:31:54 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Fri, 29 Feb 2008 15:31:54 +0100 Subject: why not bisect options? Message-ID: <47C8175A.20107@jouy.inra.fr> Hi all, I thought it would be useful if insort and consorts* could accept the same options than list.sort, especially key and cmp. The only catch I can think of is that nothing prevents a crazy developer to insort elements using different options to the same list. I foresee two courses of actions: 1) let the developer be responsible for the homogeneity of successive insort calls on the same list (remember that the developer is already responsible for giving a sorted list), or 2) make bisect a class which keeps the key and cmp options internally and always use them for comparison, something like: class Bisect: def __init__(self, lst = [], key = None, cmp = None): self.key = key self.cmp = cmp self.lst = lst self.lst.sort(key = key, cmp = cmp) def compare_elements(self, a, b): if self.cmp is not None: return self.cmp(a, b) if self.key is not None: return cmp(self.key(a), self.key(b)) return cmp(a,b) def insort_right(self, elt, lo = 0, hi = None): """Inspired from bisect in the python standard library""" if hi is None: hi = len(self.lst) while lo < hi: mid = (lo + hi) / 2 if self.compare_elements(elt, self.lst[mid]) < 0: hi = mid else: lo = mid + 1 self.lst.insert(lo, elt) ... Any thoughts about this? RB * at this point you should smile... From arnodel at googlemail.com Sun Feb 3 04:13:38 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 3 Feb 2008 01:13:38 -0800 (PST) Subject: Python feature request : operator for function composition References: Message-ID: On Feb 3, 5:09?am, Kay Schluehr wrote: > As you know, there is no operator for function composition in Python. > When you have two functions F and G and ?want to express the > composition F o G you have to create a new closure > > lambda *args, **kwd: F (G (*args, **kwd)) > > or you write a composition in functional style > > compose( F, G ) > > None of these solutions is particular terse. > > Proposal > ------------- > I want to propose overloading the logical __and__ operator i.e. '&' > for functions s.t. F & G means "compose(F,G)". This suggestion is non- > conflicting since & is not used as an operator in combination with > function objects yet: given a function object F and an arbitrary > object X the combination F & X raises a TypeError when evaluated. > > Alternatives > ----------------- > One could use other unused operators like F << G or F * G to write > terse function composition expressions. I' m not sure which one is > best and would use the proposed & if no one presents arguments against > it. What about other callable objects? -- Arnaud From mcrobertson at hotmail.com Thu Feb 28 05:02:14 2008 From: mcrobertson at hotmail.com (Michael Robertson) Date: Thu, 28 Feb 2008 02:02:14 -0800 Subject: Place n indistinguishable items into k distinguishable boxes In-Reply-To: <02c84be9-f49f-4784-a091-4e64c1a0c7e2@41g2000hsc.googlegroups.com> References: <02c84be9-f49f-4784-a091-4e64c1a0c7e2@41g2000hsc.googlegroups.com> Message-ID: castironpi at gmail.com wrote the following on 02/28/2008 12:36 AM: > On Feb 27, 8:47 pm, Michael Robertson wrote: > Your only casualty here is all the zeroes in (4,0,0,..). You don't > want to swap k_2 and k_3 in (4,0,0). (Is that what permutation > means?) Correct. Though by 'permutation', I meant 'permutations with repetitions'---so the algorithm would have handled that. > >> In addition to having to generate permutations for each integer >> partition, I'd have to ignore all integer partitions which had more than >> k parts...this seemed like a bad way to go (bad as in horribly inefficient). >> >> Better ideas are appreciated. > > Running time on my recursive was K** 2* N, counting the copy, I > think. sum( 1..i )== i( i+ 1 )/ 2, O( i** 2 ). My iterative was > slower, K** 3* N, unless you save a K or N in the small length of K > early on, I think. Did anyone take this course that can tell me? Thanks again for your efforts here. This particular problem didn't appear in any course I took...certainly similar problems did. From arkanes at gmail.com Mon Feb 4 11:23:01 2008 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 4 Feb 2008 10:23:01 -0600 Subject: Python GUI toolkit In-Reply-To: <47A735D0.9000902@codebykevin.com> References: <42c7d139-3520-4d73-85cd-f67e3bdacd5a@c4g2000hsg.googlegroups.com> <47A735D0.9000902@codebykevin.com> Message-ID: <4866bea60802040823j57314f4fpcba783a3e6a6fc49@mail.gmail.com> On Feb 4, 2008 9:57 AM, Kevin Walzer wrote: > Chris Mellon wrote: > > > Nitpick, but an important one. It emulates *look*. Not feel. Native > > look is easy and totally insufficient for a "native" app - it's the > > feel that's important. > > Is this opinion based on firsthand experience with use of the Tile/ttk > widgets on any of the relevant platforms? > > I'm not a Windows user, so I can't speak about that platform, but I have > worked very hard to make my Python-Tile-Tk app consistent with both the > look and feel of OS X: keyboard shortcuts, menu behavior, and so on. > It's mainly a matter of attention to detail, and listening to user > feedback. I've gotten good feedback on my applications in recent months > as I've implemented more and more platform native behavior, and sales of > these applications (I'm a shareware developer) reflect that. > > I'd be interested to hear how, in your experience, Tk/Tile is inherently > unable to deliver native platform "feel," in a way that reflects on the > toolkit rather than the developer. It's fine to focus on Windows if > that's your area of expertise. I didn't say inherently unable, I said the toolkit doesn't provide it. Note that you said that you did a lot of work to follow OS X conventions and implement behavior. The toolkit doesn't help you with any of this. A mac-native toolkit (or one that strives for native behavior, like wxPython) eliminates a lot of this work (although, of course, not all). From bronger at physik.rwth-aachen.de Fri Feb 22 00:44:02 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Fri, 22 Feb 2008 06:44:02 +0100 Subject: Return value of an assignment statement? References: <6d945394-739e-4c47-ad71-faaab8f9d566@34g2000hsz.googlegroups.com> <5sudnTSXrZY0aCDanZ2dnUVZ_rKtnZ2d@comcast.com> <5MSdncSVGdGriCPanZ2dnUVZ_vPinZ2d@comcast.com> Message-ID: <87skzla6l9.fsf@physik.rwth-aachen.de> Hall?chen! Jeff Schwab writes: > Aahz wrote: > >> [...] >> >> Notice very very carefully that Bruno is not using "variable". >> Many expert Python programmers strongly prefer to talk about >> "names" instead of "variables" (especially when explaining the >> Python object model) precisely because using "variable" leads to >> incorrect expectations. >> >> http://starship.python.net/crew/mwh/hacks/objectthink.html > > So what is the "variable?" Or is Python the first HLL I've ever > heard of that didn't have variables? Since Python objects, names, their operations, and the syntax used for it resemble very closely (but not completely) what is called "variable" in other languages, Python names are mostly called "variables", too. But there is this one thing of changing mutable objects which may also change the "value" of other "variables". This can only be understood if your nomenclature is strictly correct. I find Python's model is this area great. It makes many things simpler and only one or two things more complicated. I had my bad experiences with it, too (e.g. initialising two lists with "x_values=y_values=[]"). But only once per year I stumble over it. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From patrick.waldo at gmail.com Fri Feb 29 11:21:47 2008 From: patrick.waldo at gmail.com (patrick.waldo at gmail.com) Date: Fri, 29 Feb 2008 08:21:47 -0800 (PST) Subject: joining strings question References: <6b41eaf1-05e1-4b04-8c31-6737166f267f@b1g2000hsg.googlegroups.com> Message-ID: I tried to make a simple abstraction of my problem, but it's probably better to get down to it. For the funkiness of the data, I'm relatively new to Python and I'm either not processing it well or it's because of BeautifulSoup. Basically, I'm using BeautifulSoup to strip the tables from the Federal Register (http://www.access.gpo.gov/su_docs/aces/fr- cont.html). So far my code strips the html and gets only the departments I'd like to see. Now I need to put it into an Excel file (with pyExcelerator) with the name of the record and the pdf. A snippet from my data from BeautifulSoup like this: ['Environmental Protection Agency', 'RULES', 'Approval and Promulgation of Air Quality Implementation Plans:', 'Illinois; Revisions to Emission Reduction Market System, ', '11042 [E8-3800]', 'E8-3800.pdf', 'Ohio; Oxides of Nitrogen Budget Trading Program; Correction, ', '11192 [Z8-2506]', 'Z8-2506.pdf', 'NOTICES', 'Agency Information Collection Activities; Proposals, Submissions, and Approvals, ', '11108-11110 [E8-3934]', 'E8-3934.pdf', 'Data Availability for Lead National Ambient Air Quality Standard Review, ', '11110-11111 [E8-3935]', 'E8-3935.pdf', 'Environmental Impacts Statements; Notice of Availability, ', '11112 [E8-3917]', 'E8-3917.pdf'] What I'd like to see in Excel is this: 'Approval and Promulgation of Air Quality Implementation Plans: Illinois; Revisions to Emission Reduction Market System, 11042 [E8-3800]' | 'E8-3800.pdf' | RULES 'Ohio; Oxides of Nitrogen Budget Trading Program; Correction, 11192 [Z8-2506]' | 'Z8-2506.pdf' | RULES 'Agency Information Collection Activities; Proposals, Submissions, and Approvals, 11108-11110 [E8-3934]' | 'E8-3934.pdf' | NOTICES 'Data Availability for Lead National Ambient Air Quality Standard Review, 11110-11111 [E8-3935]' | 'E8-3935.pdf' | NOTICES 'Environmental Impacts Statements; Notice of Availability, 11112 [E8-3917]' | 'E8-3917.pdf' | NOTICES etc...for every department I want. Now that I look at it I've got another problem because 'Approval and Promulgation of Air Quality Implementation Plans:' should be joined to both Illinois and Ohio...I love finding these little inconsistencies! Once I get the data organized with all the titles joined together appropriately, outputting it to Excel should be relatively easy. So my problem is how to join these titles together. There are a couple patterns. Every law is followed by a number, which is always followed by the pdf. Any ideas would be much appreciated. My code so far (excuse the ugliness): import urllib import re, codecs, os import pyExcelerator from pyExcelerator import * from BeautifulSoup import BeautifulSoup as BS #Get the url, make the soup, and get the table to be processed url = "http://www.access.gpo.gov/su_docs/aces/fr-cont.html" site = urllib.urlopen(url) soup = BS(site) body = soup('table')[1] tds = body.findAll('td') mess = [] for td in tds: mess.append(str(td)) spacer = re.compile(r'.*') data = [] x=0 for n, t in enumerate(mess): if spacer.match(t): data.append(mess[x:n]) x = n dept = re.compile(r'.*') title = re.compile(r'.*') title2 = re.compile(r'.*') none = re.compile(r'None') #Strip the html and organize by department group = [] db_list = [] for d in data: pre_list = [] for item in d: if dept.match(item): dept_soup = BS(item) try: dept_contents = dept_soup('a')[0]['name'] pre_list.append(str(dept_contents)) except IndexError: break elif title.match(item) or title2.match(item): title_soup = BS(item) title_contents = title_soup.td.string if none.match(str(title_contents)): pre_list.append(str(title_soup('a')[0]['href'])) else: pre_list.append(str(title_contents)) elif link.match(item): link_soup = BS(item) link_contents = link_soup('a')[1]['href'] pre_list.append(str(link_contents)) db_list.append(pre_list) for db in db_list: for n, dash_space in enumerate(db): dash_space = dash_space.replace('–','-') dash_space = dash_space.replace(' ', ' ') db[n] = dash_space download = re.compile(r'http://.*') for db in db_list: for n, pdf in enumerate(db): if download.match(pdf): filename = re.split('http://.*/',pdf) db[n] = filename[1] #Strip out these departments AgrDep = re.compile(r'Agriculture Department') EPA = re.compile(r'Environmental Protection Agency') FDA = re.compile(r'Food and Drug Administration') key_data = [] for list in db_list: for db in list: if AgrDep.match(db) or EPA.match(db) or FDA.match(db): key_data.append(list) #Get appropriate links from covered departments as well LINK = re.compile(r'^#.*') links = [] for kd in key_data: for item in kd: if LINK.match(item): links.append(item[1:]) for list in db_list: for db in list: if db in links: key_data.append(list) print key_data[1] On Feb 29, 4:35 pm, Steve Holden wrote: > patrick.wa... at gmail.com wrote: > > Hi all, > > > I have some data with some categories, titles, subtitles, and a link > > to their pdf and I need to join the title and the subtitle for every > > file and divide them into their separate groups. > > > So the data comes in like this: > > > data = ['RULES', 'title','subtitle','pdf', > > 'title1','subtitle1','pdf1','NOTICES','title2','subtitle2','pdf','title3','subtitle3','pdf'] > > > What I'd like to see is this: > > > [RULES', 'title subtitle','pdf', 'title1 subtitle1','pdf1'], > > ['NOTICES','title2 subtitle2','pdf','title3 subtitle3','pdf'], etc... > > > I've racked my brain for a while about this and I can't seem to figure > > it out. Any ideas would be much appreciated. > > > Thanks > > data = ['RULES', 'title','subtitle','pdf', > 'title1','subtitle1','pdf1','NOTICES','title2','subtitle2','pdf','title3','subtitle3','pdf'] > olist = [] > while data: > if data[0] == data[0].upper(): > olist.append([data[0]]) > del data[0] > else: > olist[-1].append(data[0]+' '+data[1]) > olist[-1].append(data[2]) > del data[:3] > print olist > > However, I suspect you should be asking yourself whether this is really > an appropriate data structure for your needs. If you say what you are > trying to achieve in the large rather than focusing on a limited > programming issue there may be much better solutions. > > I suspect, for example, that a dict indexed by the categories and with > the entries each containing a list of tuples might suit your needs much > better, i.e. > > { > 'RULES': [('title subtitle', 'pdf'), > ('title1 subtitle1', 'pdf')], > 'NOTICES': [('title2 subtitle2', 'pdf'), > 'title3 subtitle3', 'pdf')]} > > One final observation: if all the files are PDFs then you might just as > well throw the 'pdf' strings away and use a constant extension when you > try and open them or whatever :-). Then the lists of tuples i the dict > example could just become lists of strings. > > regards > Steve > > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC http://www.holdenweb.com/ From steve at REMOVE-THIS-cybersource.com.au Tue Feb 5 16:54:02 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Tue, 05 Feb 2008 21:54:02 -0000 Subject: Why not a Python compiler? References: <28eead2f-a40c-414b-bd3d-a941f8a851a2@d70g2000hsb.googlegroups.com> <5fcaf0c4-c1b8-425e-82e2-f9136f890a9f@1g2000hsl.googlegroups.com> Message-ID: <13qhmnq9f2vdo2c@corp.supernews.com> On Tue, 05 Feb 2008 13:22:13 -0800, Ripter001 at gmail.com wrote: > On Feb 5, 11:44 am, Steve Holden wrote: >> Ripter... at gmail.com wrote: >> >> Why not a Python COMPILER? >> >> > What about a Python JIT hardware chip, so the CPU doesn't have to >> > translate. Although it seems to me that with today's dual and quad >> > core processors that this might be a mute point because you could >> > just use one of the cores. >> >> What about a chip that reads your mind and does what you want it to? >> >> I am sure that would be popular with all the frustrated computer users >> there are in the world. >> >> regards >> Steve >> -- >> Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC >> http://www.holdenweb.com/ > > I'm not sure where that came from. Microsoft had talked about a hardware > JIT for .NET a few years back. I was just wondering if anyone had > thought of it for python or anything like that. Okay, you know how hard it is to create a software JIT compiler for a language as dynamic as Python? It's REALLY HARD, which is why it hasn't already been done[1]. Now you want that done in *hardware*, which is much harder. Who's going to spend the money on R&D? I'm sure there are thousands of l33t hax0rs out there who have thought "Wouldn't it be c00l if there was a chip I could put into my PC to make Python run a million times faster!!!". When I was younger and more stupi^W innocent I had a mad fegairy for Forth and Lisp chips, but their lack of financial viability and their unfortunate habit of actually being *slower* than running the language in software put a big dent in the idea. As general purpose CPUs got faster, the idea of making a specialist language chip is now pretty much dead. Even if you could find a niche market prepared to pay for it, "people who run Python programs" is probably not that market. [1] Apart from some specializing compilers like Pysco http://psyco.sourceforge.net/introduction.html -- Steven From castironpi at gmail.com Wed Feb 20 19:53:21 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 20 Feb 2008 16:53:21 -0800 (PST) Subject: The big shots References: <89d15587-e8de-444c-b240-4a10305146e0@e23g2000prf.googlegroups.com> <3c035ede-d98b-4adc-bde4-5a918bd04dd8@h25g2000hsf.googlegroups.com> <586b3c9c-6b8b-4fce-9307-4984b857276a@s37g2000prg.googlegroups.com> <87ir0jgor9.fsf@benfinney.id.au> Message-ID: <4f3c8b44-9ba6-4901-a0fe-4f2de0ce0b2b@q70g2000hsb.googlegroups.com> On Feb 20, 6:02?pm, Ben Finney wrote: > castiro... at gmail.com writes: > > My writing isn't unclear > > Please re-assess that statement in light of the dozens of responses > from many people in the last few weeks, telling you that your writing > *is* unclear. > > For what it's worth, I've found none of your threads in the last few > weeks to make much sense at all, because of unclear and incoherent > writing. On that basis, I dismiss them before trying to re-read them, > because I don't want to spend my time trying to find sense in them > that may not be there at all. > > -- > ?\ ? ? ? "From the moment I picked your book up until I laid it down I | > ? `\ ? ?was convulsed with laughter. Someday I intend reading it." ?-- | > _o__) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Groucho Marx | > Ben Finney How do I "bake" this idea? Steve Bethard has often asked, "When would you use it?" and "What is a use case?" Is the hang up on this specific idea the absence of possibilities of use? Does he just want to see some fleshed out? Is it easier to consider the abstraction in a particular example? If the example isn't good, is the idea rejected, or the example replaced? Is that the hang-up of this one? Surely, there's a demand for performance, but what next? I'll distill it. import ext ext.FuncA= """[string in C/C++]""" ext.propogate() dosomething( ext.FuncA() ) The style is wide open. Should each function you add be an object? ext.FuncA= ext.Compile.C( """[string]""" )? Should 'propogate' be called on initialization, or separately? I intended the above to be a proof of concept; not only is it possible, it's possible in Python "as is." Design the back end first, or the interface? Having the proof of concept makes that question more tangible and "grappleable", if that's a word. I don't even know if I care who gets credit. The idea is currently half baked. (Say that first next time, right?!) Not finished. Are further problems a) miscommunication or b) absence of content? If Holden and Genellina don't follow, that's a strong sign that the structure of my proposals is really bad, even if there's a good thing behind it. You just have to solve (a) before you solve (b), which makes devoting resources to (a) a little preliminary. From codemonkey at nowhere.org Thu Feb 21 01:20:05 2008 From: codemonkey at nowhere.org (TerryP) Date: Thu, 21 Feb 2008 01:20:05 -0500 Subject: Article of interest: Python pros/cons for the enterprise References: <2f1527a7-2f66-44c7-9665-4d8ff01fa5ab@28g2000hsw.googlegroups.com> Message-ID: Thanks for the link, was a nice read. "Have specialized needs better served by other languages that you already know. For example, if you want to do a lot of text processing and you have a basement full of Perl programmers, there's no compelling reason to switch." Now that really hits the sweet spot hehe. The threads topic reminds me of a project I had in mind not so long ago, I wanted to write it in Ruby because I could get it done in a few hours and move on to other work but chose not to because I could not find a way to /100%/ secure some information that had to be both kept classified and apart of the program for business reasons. So obviously ANSI C and the hunt for a suitable networking library to fill in the biggest time waster came to mind. Then I remembered any one we wanted to *prevent* getting that information out of the Ruby scripts could do the same with a little (easy) forensics work if the application was done in C or C++. So choosing a language like Ruby or Python wouldn't be much worse for the situation. Needless to say I went back to using languages on a scale of best shoe to fit first and the project got side-stepped by new hardware and a stop-gap in a can. -- The young Georgia miss came to the hospital for a checkup. "Have you been X-rayed?" asked the doctor. "Nope," she said, "but ah've been ultraviolated." From bignose+hates-spam at benfinney.id.au Mon Feb 11 17:45:01 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 12 Feb 2008 09:45:01 +1100 Subject: AttributeError: 'module' object has no attribute 'letters' References: Message-ID: <87lk5r15aq.fsf@benfinney.id.au> black_13 writes: > what does this error mean? > [...] > valid_identifier_chars = string.letters + string.digits + "_" > AttributeError: 'module' object has no attribute 'letters' It means that you're trying to access the attribute 'letters' on a module that doesn't have that attribute. You need to find what the value of 'string' is at that point in the code. If I had to guess, I would say the person who wrote the above line was expecting 'string' to be bound to the Python standard library module 'string'; but that the code you have binds that name to some other module. -- \ "War is God's way of teaching geography to Americans." -- | `\ Ambrose Bierce | _o__) | Ben Finney From simon at brunningonline.net Fri Feb 22 08:57:42 2008 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 22 Feb 2008 13:57:42 +0000 Subject: Sending key-presses to other programs on Windows, and settings of controls? In-Reply-To: References: Message-ID: <8c7f10c60802220557m588c872cic685ac4760aac057@mail.gmail.com> On Thu, Feb 21, 2008 at 1:20 PM, Tim van der Leeuw wrote: > I'm looking for ways to send keypresses to another application on Windows > XP, and to set values of Windows Controls (all of them text-boxes). Try . -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues From cokofreedom at gmail.com Wed Feb 13 03:07:00 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 13 Feb 2008 00:07:00 -0800 (PST) Subject: OT: Speed of light [was Re: Why not a Python compiler?] References: <6f-dnfwZwvz6Ui3anZ2dnUVZ_oOnnZ2d@speakeasy.net> <13r2p6aivk1no9a@corp.supernews.com> <880dece00802121311n77f73515ve7db8a931825d958@mail.gmail.com> <8fGdnVvzR-CcBy_anZ2dnUVZ_rqlnZ2d@speakeasy.net> Message-ID: <556c4dc4-e5dc-434f-8afe-eddab4669046@e23g2000prf.googlegroups.com> > And the rest of us just use SI. (And if you bring up the > _kilogram-force_, I'll just cry.) SI = Super Incredible? Awesome name for Force/Mass / NewItemOfClothing2050! From rocksportrocker at googlemail.com Wed Feb 27 07:33:35 2008 From: rocksportrocker at googlemail.com (rocksportrocker) Date: Wed, 27 Feb 2008 04:33:35 -0800 (PST) Subject: BaseHTTPServer and do_POST method Message-ID: <0215927e-0d35-4b97-b5b1-bc46cd6f3b88@64g2000hsw.googlegroups.com> Hi, I am trying to implement a local server for storing and retrieving numerical data. So I use BaseHTTPServer as follows: --------------------------------------------------------- from BaseHTTPServer import * class Handler(BaseHTTPRequestHandler): def do_POST(self): print "POST" self.send_response(200) httpd = HTTPServer(("",8000), Handler) httpd.serve_forever() --------------------------------------------------------- For testing I use: --------------------------------------------------------- import httplib data = "123456789o" * 100 conn = httplib.HTTPConnection("localhost:8000") print conn.request("POST", "/", data) --------------------------------------------------------------- Executing this client, the server says: error(10053, 'Software caused connection abort') If I add "conn.getresponse()" at the end of the test script, the message disapears, but the server hangs. Where is my mistake ? Greetings, Uwe. From steve at holdenweb.com Sun Feb 3 09:26:14 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 03 Feb 2008 09:26:14 -0500 Subject: GUI definition for web and desktop In-Reply-To: References: Message-ID: Guilherme Polo wrote: > 2008/2/3, Steve Holden : >> Daniel Fetchinson wrote: >> > Hi pythoneans, >> > >> > I'm looking for a simple text based GUI definition format and [...] >> I believe Glade produces XML descriptions of its interfaces, so wxGlade >> would be one possible starting-point. >> > > Glade does, but dont confuse it with wxGlade. wxGlade can generate > direct python code or XRC files. > So what are you telling me - that XRC files aren't XML? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From petercable at gmail.com Fri Feb 15 09:06:09 2008 From: petercable at gmail.com (petercable at gmail.com) Date: Fri, 15 Feb 2008 06:06:09 -0800 (PST) Subject: copying files through Python References: <15736d7f-fc9f-46a6-8d21-51ed77526944@h11g2000prf.googlegroups.com> Message-ID: <4e060b62-e537-44a6-8e98-8b8b1ab9a063@e6g2000prf.googlegroups.com> On Feb 13, 10:50?pm, Lalit wrote: > I need to write a program which would transfer files under one folder > structure (there are sub folders) to single folder. find /fromdir -exec mv {} /todir \; -print Pete From grante at visi.com Fri Feb 1 19:52:09 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 02 Feb 2008 00:52:09 -0000 Subject: Win32 python: odd behavior when run via ssh References: <13q74q7bpoqro15@corp.supernews.com> Message-ID: <13q7flpp1ep9ca4@corp.supernews.com> On 2008-02-02, Ross Ridge wrote: >>When I ssh into a windows machine (running Cygwin sshd), I can >>invoke python at the shell prompt (you have to use -i option >>and I don't really understand why). >> >>Once it's started there are couple rather odd behaviors: >> >> 1) readline support doesn't work. > > My guess is either that Cygwin version of Python you invoked doesn't > think that stdin/stdout is attached to a tty (ie. the pseudo-terminal > that sshd should create), or you're using official Win32 "native" Python > distribution Python and it doesn't think stdin/stdout is attached to > a console. The latter. I guess I forgot to say I was running the normal Win32 python. > If you're using the Cygwin version of Python than it's > probably bug. If you're using the offficial Win32 port of > Python than you probably want to use the Cygwin version > because Win32 version doesn't support readline anyways. That's odd, because readline seems to work fine in a Windows console (recalling previous lines and line editing). -- Grant Edwards grante Yow! Do you guys know we at just passed thru a BLACK visi.com HOLE in space? From skip at pobox.com Thu Feb 7 17:10:02 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 7 Feb 2008 16:10:02 -0600 Subject: Looking for SpamBayes feedback/help Message-ID: <18347.33210.461474.16505@montanaro-dyndns-org.local> Kim Komando recommended SpamBayes (a Python-based Bayesian spam filter - http://www.spambayes.org/) today to her readers/listening audience: http://www.komando.com/coolsites/ On one level this is very gratifying. On another level it's created a whole new set of requests like "Does SpamBayes work with Razzmatazz Mail?" We're getting a little inundated and I was hoping to get some help. One question I've seen multiple times in a couple different guises is "Does SpamBayes work with Internet mail programs?" Most of these people seem to be using Yahoo, Gmail, AOL and the like. I'm almost certain that it won't work with AOL since that is a completely closed system. I suspect the same to be true of Hotmail. I use it with Gmail via their POP interface, but have no experience with their IMAP interface. I know nothing about the mail transfer capabilities of Yahoo or Hotmail. If you use any of these systems for reading mail, can you take a moment to answer a couple questions for me (private mail is fine)? 1. Does support POP3 or IMAP? 2. Have you attempted to use SpamBayes with ? 3. If so, were you successful? I'm going to craft a little table for the SpamBayes FAQ page and it will save me a bunch of time if I don't have to go wandering in the twisty little mazes that are Internet mail sites. Thanks, -- Skip Montanaro - skip at pobox.com - http://www.webfast.com/~skip/ From rpglover64 at gmail.com Fri Feb 15 15:46:59 2008 From: rpglover64 at gmail.com (rpglover64 at gmail.com) Date: Fri, 15 Feb 2008 12:46:59 -0800 (PST) Subject: Assignment saves time? References: <87bq6iphua.fsf@mulj.homelinux.net> <45fe7ed2-0cd6-4287-a81c-63749041e8d0@e23g2000prf.googlegroups.com> Message-ID: <6bee126f-ffc5-4942-9f15-d0c34a8de42f@64g2000hsw.googlegroups.com> I ran it in an interactive python shell, which might have made a difference. import timeit time1=timeit.Timer('s=len(li); s==1000', 'li=range(1000)') time2=timeit.Timer('len(li)==1000', 'li=range(1000)') store=min(time1.repeat(5)) call=min(time2.repeat(5)) store=min(min(time1.repeat(5)),store) call=min(min(time2.repeat(5)),call) store 0.25531911849975586 call 0.25700902938842773 The difference is small enough to be insignificant, but I am curious how it's possible and why it happened. It's more likely a reflection of how I timed it than anything else, isn't it? From BjornSteinarFjeldPettersen at gmail.com Sat Feb 23 20:19:47 2008 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Sat, 23 Feb 2008 17:19:47 -0800 (PST) Subject: Simple - looking for a way to do an element exists check.. References: <7x8x1c25cz.fsf@ruckus.brouhaha.com> <7x3ark2560.fsf@ruckus.brouhaha.com> <1ea39cd9-ed63-401e-8ff7-88ffbd49be50@d5g2000hsc.googlegroups.com> Message-ID: <08d42769-8d22-4f9b-af00-e7d4cb511568@m23g2000hsc.googlegroups.com> On Feb 23, 6:18 pm, Paul Hankin wrote: > On Feb 22, 7:01 pm, Paul McGuire wrote: > > > On Feb 22, 12:54 pm, Paul Rubin wrote: > > > > Paul Rubin writes: > > > > if any(x==element[0] for x in a): > > > > a.append(element) > > > > Should say: > > > > if any(x[0]==element[0] for x in a): > > > a.append(element) > > > I think you have this backwards. Should be: > > > if not any(x[0]==element[0] for x in a): > > a.append(element) > > IMO Jason's solution of testing containment in a generator is better > (more readable). > if element[0] not in (x[0] for x in a): > a.append(element) > > -- > Paul Hankin It may be more readable (although that's debatable), but it always traverses the entire list. If the list is short I'd use either the traditional "for/else" or the newer "if all(...)": if all(x[0] != element[0] for x in a): a.append(element) which allows for short-circuit evaluation -- I generally try to stay away from negating any() and all() because the logic often gets convoluted. If the lists are long enough to care, either rewrite use a set-based solution if the items are hashable, or keep the elements sorted and rewrite to use the bisect module if the elements can be ordered. -- bjorn From bharathv6 at gmail.com Thu Feb 21 01:10:12 2008 From: bharathv6 at gmail.com (bharath venkatesh) Date: Thu, 21 Feb 2008 11:40:12 +0530 Subject: configuration and limitation of memcache.. Message-ID: <910313af0802202210n534da95fua52a42ea2868e104@mail.gmail.com> hi, In my project i need to store lot n lots of images in my cache and retrieve it very frequently.. currently i am using memcache to store and retreive images from cache... i will be using 4 GB ram as cache and each image won't exceed 1 mb for sure ...and i came across that memcache will be assigned only certain amount of cache for caching ... so how to configure it so that it can use the amount of cache as much as i want like 3 GB of ram ... and also i want to know whether memcache is the right way to go about my project .. i have already implemented storing and retrieving images using images ... it is working fine .. and i find it easy as images can be stored and retrieved using a key and that is what i want ... but my project will have many clients storing and retrieving images concurrently ... so i want to know whether memcahe is the right way .. does it have any limitation ...if so pls suggest an alternative ....as i doing my project in python suggest an alternative which can be interfaced with python easily -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Sun Feb 17 04:03:29 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 17 Feb 2008 04:03:29 -0500 Subject: sockets -- basic udp client In-Reply-To: <7xk5l4ujn2.fsf@ruckus.brouhaha.com> References: <37cfdc95-5aa0-4b47-9dc6-d54f7ac254a6@v3g2000hsc.googlegroups.com> <8f768bd3-ec74-4f0d-bbc2-4407b2d7b46a@60g2000hsy.googlegroups.com> <7xk5l4ujn2.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "rluse1 at gmail.com" writes: >> Historically, though, the ultimate authority on this kind of stuff is >> Richard Stevens and his Unix and TCP/IP books >> >> I recommend these books if you want to get into network programming. > > I keep wanting to get that book, but it gets older and older. Have > things really not changed since it was written? TCP is much like a funicular railway: it's been around long enough that the basic engineering principles are known and the basic bugs have been ironed out. Stevens is still an excellent reference. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From danb_83 at yahoo.com Sun Feb 10 20:17:46 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Sun, 10 Feb 2008 17:17:46 -0800 (PST) Subject: Reducing types References: Message-ID: <4eab9e37-fb9d-4674-80c6-e93a1a4b788a@s37g2000prg.googlegroups.com> On Feb 10, 1:19 pm, bearophileH... at lycos.com wrote: > For me Python is useful to write code that gives *correct* results, > allowing me to write it in a short & simple way, with quick debugging > cycles (and for other purposes, like to write dynamic code, to use it > as glue language to use libraries, to create quick GUIs, as scripting > for data munging, etc). When I need more speed I use the D language, > or Psyco, or C, etc. > > Python 2.5 has string, unicode, long, int, float, and Decimal types. > Python 3.0 reduces them to string (+ the byte type) int, float, and > Decimal. So why not adopt the Decimal (IEEE 854) as the standard > "float" for Python (if speed is a concern, than a mfloat type may be > introduced, it's a "machine float", it's essentially the "float" of > Python 2.5, operations between a float and a mfloat give a mfloat)? It > can reduce some FP bugs, and avoid those 5.89 + 3.99 = > 9.879999999999999 bugs that puzzle newbies, that are okay in a very > fast low-level language like C++, but probably unfit for a high-level > one :-) (1) Because, although speed may not be the primary focus of Python, it's still relevant. And float has a HUGE speed advantage over Decimal. (2) Because decimal arithmetic isn't a panacea for floating-point errors. I have a decimal calculator at hand, and while it gives the correct result for 5.89 + 3.99, it gives slightly incorrect results for 1/3*3 and sqrt(3)**2. From pDOTpagel at helmholtz-muenchen.de Wed Feb 27 07:19:51 2008 From: pDOTpagel at helmholtz-muenchen.de (Philipp Pagel) Date: Wed, 27 Feb 2008 12:19:51 +0000 (UTC) Subject: How to pass shell variable to shell script from python References: Message-ID: Gerardo Herzig wrote: > Rockins Chen wrote: > Well, if you have to use os.system, that could be > os.system("export target=localhost.localdomain.org; ./callee.sh") Or os.system("env target=localhost.localdomain.org ./callee.sh") cu Philipp -- Dr. Philipp Pagel Lehrstuhl f. Genomorientierte Bioinformatik Technische Universit?t M?nchen http://mips.gsf.de/staff/pagel From goldsz at gmail.com Sat Feb 16 17:40:07 2008 From: goldsz at gmail.com (Zack) Date: Sat, 16 Feb 2008 17:40:07 -0500 Subject: class static variables and __dict__ Message-ID: If I have a class static variable it doesn't show up in the __dict__ of an instance of that class. class C: n = 4 x = C() print C.__dict__ {'__module__': '__main__', '__doc__': None, 'n': 4} print x.__dict__ {} This behavior makes sense to me as n is not encapsulated in x's namespace but what method can you use on x to find all available attributes for that class? -- Zack From gagsl-py2 at yahoo.com.ar Mon Feb 4 17:56:02 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 04 Feb 2008 20:56:02 -0200 Subject: extending python with array functions References: <47a7793b$0$85781$e4fe514c@news.xs4all.nl> Message-ID: En Mon, 04 Feb 2008 18:44:42 -0200, Janwillem escribi?: > I want to make numerical functions that can be called from python. > I am programming in pascal the last few decades so I had a look at > "python for delphi" (P4D). The demo09 gives as example add(a,b) using > integers and pyarg_parsetuple. That works! > > However, I cannot figure out what to do when a, b and the result are > arrays (or matrices) of float (for i:=0 to high(a) do c[i]:=a[i]+b[i]; > and then return c to python). Although from the ALGOL60 school and > always tried to keep far from pointers, I might also understand advise > in C. First: do you know NumPy? http://numpy.scipy.org/ NumPy provides powerful functions to work with numeric arrays. Maybe using this library you don't even have to write an extension and you can keep all your code in Python with reasonable speed. It may be the best option depending on your needs. In case you still have to write an extension: - the "usual" container for Python objects is a "list"; it's a generic container and can hold any kind of objects, but there are other alternatives too. To access its elements from Delphi, use the PySequence_XXX family of functions (or PyList_XXX if you know it is an actual list). - the array module http://docs.python.org/lib/module-array.html provides homogeneuos arrays that may be more efficient for your application. arrays don't have a special API, you have to import the module and use its functions the same as one would do in pure Python. -- Gabriel Genellina From steve at REMOVE-THIS-cybersource.com.au Tue Feb 26 17:02:24 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Tue, 26 Feb 2008 22:02:24 -0000 Subject: How about adding rational fraction to Python? References: <0d1955fc-762c-44e1-a5d8-372c71458455@p25g2000hsf.googlegroups.com> <36204e6f-0d82-449b-8ca5-c819ace9a55a@p73g2000hsd.googlegroups.com> <9503b14b-7bd5-42b4-b3f7-673d0ebd7feb@c33g2000hsd.googlegroups.com> <602ac27c-4aaa-49b2-bee2-1e0e0c705983@i7g2000prf.googlegroups.com> <1204034122.3318.3.camel@aalcdl07.lib.unc.edu> <20080226100824.fdc81ac7.darcy@druid.net> <1204051178.4191.11.camel@aalcdl07.lib.unc.edu> <20080226135152.6991f09b.darcy@druid.net> <1204053380.5087.7.camel@aalcdl07.lib.unc.edu> Message-ID: <13s933g6i0qlp3c@corp.supernews.com> On Tue, 26 Feb 2008 14:46:04 -0500, D'Arcy J.M. Cain wrote: > I am really having a hard time accepting that "TRUTH (tm)" is determined > by election. But you're apparently perfectly comfortable that "TRUTH (tm)" is decided by fiat. -- Steven From steve at holdenweb.com Fri Feb 15 11:46:39 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 15 Feb 2008 11:46:39 -0500 Subject: Accessing Oracle/Access database py2.4 In-Reply-To: <14A2A120D369B6469BB154B2D2DC34D20A24E7ED@EXCHVS01.ad.sfwmd.gov> References: <14A2A120D369B6469BB154B2D2DC34D20A24E7ED@EXCHVS01.ad.sfwmd.gov> Message-ID: Ahmed, Shakir wrote: > I was used import odbc to connect oracle or access table before, now I > switched to python 2.4 and is giving me error message. I appreciate any > help on that. > So this error message is a secret? One possibility is that you are trying to use a 2.3 extension module with 2.4 - that would give you problems. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From nicola.musatti at gmail.com Mon Feb 25 08:29:14 2008 From: nicola.musatti at gmail.com (Nicola Musatti) Date: Mon, 25 Feb 2008 05:29:14 -0800 (PST) Subject: Article of interest: Python pros/cons for the enterprise References: <2f1527a7-2f66-44c7-9665-4d8ff01fa5ab@28g2000hsw.googlegroups.com><47bd4a24$0$25225$426a74cc@news.free.fr> <036e93e6-5840-4a3c-8642-67a0a9ec44f2@i7g2000prf.googlegroups.com> <784ec210-f389-4a15-b458-961100de9103@v3g2000hsc.googlegroups.com> Message-ID: <5d351937-e1bc-44ab-810d-11f226793b2e@b29g2000hsa.googlegroups.com> On Feb 24, 9:14 pm, Larry Bugbee wrote: > On Feb 21, 10:22 am, Nicola Musatti wrote: > > > On Feb 21, 6:31 pm, Paul Boddie wrote: > > > > The main reason why C++ has declined in usage is because almost > > > everything of practical value is optional. > > No, disagree. > > > The main reason why C++ has declined in usage is because it never got > > the kind of corporate marketing enjoyed by Java and C#. > > I'm inclined to disagree for two reasons. C++ is a very complex > language. Java (and the later C#) less so. Couple that with reduced > debugging time due to garbage collection and fewer pointer problems, a > lot of us decided a factor of 2x in personal productivity was worth > it. Runtime was initially an impediment, and still is for desktop > applications, but the trade was worth it. While this was probably true towards the end of the nineties, given the standard library and Boost I find it hard to believe that a similar increase can be accounted for just in terms of language differences. > Corporate marketing, and corporate attention in general, saw to it > that Java was well equipped with libraries and frameworks addressing > enterprise application needs. ...but the *big* reason Java won over C+ > + is because your application became stable sooner. ...with arguably > fewer problems later. The number of libraries you get "out of the box" appear to me as more likely explanations for the productivity increase. > And the migration to Python is due in large part because of an > additional factor of 3-4x in personal productivity (over Java). > Improvements in runtime performance wouldn't hurt, but for many > applications that's not an issue. (If optional data typing were > offered, Python's penetration in the enterprise space would be even > higher, and I suspect there would be performance gains as well.) This I found less hard to believe. Python is more expressive than Java and usually requires less code for the same task. Moreover tha availability of libraries is comparable. Cheers, Nicola Musatti From loic.berthe at free.fr Sun Feb 10 07:44:27 2008 From: loic.berthe at free.fr (Elby) Date: Sun, 10 Feb 2008 13:44:27 +0100 Subject: Plotting 3d points In-Reply-To: <47aed3e6$0$90273$14726298@news.sunsite.dk> References: <47aed3e6$0$90273$14726298@news.sunsite.dk> Message-ID: <1202647467.4028.3.camel@bluelagoon> Matplotlib as some 3D capabilities too. You can have a look at these examples : http://scipy.org/Cookbook/Matplotlib/mplot3D From kay.schluehr at gmx.net Sun Feb 3 04:43:38 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sun, 3 Feb 2008 01:43:38 -0800 (PST) Subject: Python feature request : operator for function composition References: Message-ID: <83631748-4190-47f6-acff-6afb363c3ea5@c23g2000hsa.googlegroups.com> On 3 Feb., 10:13, Arnaud Delobelle wrote: > On Feb 3, 5:09 am, Kay Schluehr wrote: > > > > > As you know, there is no operator for function composition in Python. > > When you have two functions F and G and want to express the > > composition F o G you have to create a new closure > > > lambda *args, **kwd: F (G (*args, **kwd)) > > > or you write a composition in functional style > > > compose( F, G ) > > > None of these solutions is particular terse. > > > Proposal > > ------------- > > I want to propose overloading the logical __and__ operator i.e. '&' > > for functions s.t. F & G means "compose(F,G)". This suggestion is non- > > conflicting since & is not used as an operator in combination with > > function objects yet: given a function object F and an arbitrary > > object X the combination F & X raises a TypeError when evaluated. > > > Alternatives > > ----------------- > > One could use other unused operators like F << G or F * G to write > > terse function composition expressions. I' m not sure which one is > > best and would use the proposed & if no one presents arguments against > > it. > > What about other callable objects? > > -- > Arnaud Supporting general callables would be very fine. I thing a callable ABC with two protocols named __call__ and __compose__ would be most adequate. I'm just not sure if Python 2.X requires a more ad hoc implementation for builtin callable types? On the level of user defined classes a bundling between __call__ and __compose__ shall remain optional ( unlike e.g. the dependency between __iter__ and __next__ for iterables ). From williambattersea at gmail.com Tue Feb 12 19:19:31 2008 From: williambattersea at gmail.com (williambattersea at gmail.com) Date: Tue, 12 Feb 2008 16:19:31 -0800 (PST) Subject: Getting Wireless Signal Strength / Windows XP Message-ID: Hello, I'm looking for a way to get wireless signal strength on Windows XP with Python. I see there's a library for Linux, but I can't find anything for windows. However, I see that using WMI I can access it in theory at least, using a query like "select Ndis80211ReceivedSignalStrength from MSNdis_80211_ReceivedSignalStrength where active=true" (I got this from: http://www.dotnet247.com/247reference/msgs/36/181397.aspx) I just began playing with the WMI library, but I can't get a hold of the signal strength. As far as I can tell, I should be able to get a handle on it with: import wmi c = wmi.WMI() wql = "select Ndis80211ReceivedSignalStrength from MSNdis_80211_ReceivedSignalStrength where active=true" o = c.query(wql) But I get an error. Traceback (most recent call last): File "", line 1, in c.query("select Ndis80211ReceivedSignalStrength from MSNdis_80211_ReceivedSignalStrength where active=true") File "C:\Python25\Lib\site-packages\wmi.py", line 889, in query return [ _wmi_object (obj, instance_of, fields) for obj in self._raw_query(wql) ] File "C:\Python25\lib\site-packages\win32com\client\util.py", line 83, in next return _get_good_object_(self._iter_.next()) com_error: (-2147217392, 'OLE error 0x80041010', None, None) Is this not available to me? Any ideas? Am I going about this in the wrong way? Thanks From python.list at tim.thechases.com Fri Feb 15 16:43:21 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 15 Feb 2008 15:43:21 -0600 Subject: Help Parsing an HTML File In-Reply-To: <15f9198f-fa2a-4f4f-8f87-7402b03743e1@s13g2000prd.googlegroups.com> References: <15f9198f-fa2a-4f4f-8f87-7402b03743e1@s13g2000prd.googlegroups.com> Message-ID: <47B60779.1050105@tim.thechases.com> > I need to parse the file in such a way to extract data out of the html > and to come up with a tab separated file that would look like OUTPUT- > FILE below. BeautifulSoup[1]. Your one-stop-shop for all your HTML parsing needs. What you do with the parsed data, is an exercise left to the reader, but it's navigable. -tkc [1] http://www.crummy.com/software/BeautifulSoup/ From gagsl-py2 at yahoo.com.ar Mon Feb 25 19:32:19 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 25 Feb 2008 22:32:19 -0200 Subject: Backup Script over ssh References: Message-ID: En Thu, 21 Feb 2008 09:32:23 -0200, Christian Kortenhorst escribi?: > I am new to python and the list. Welcome? > I want to create backup script for my windows PC and upload to Linux > server > over ssh but whats the best way to go about this. rsync? No need to reinvent the wheel... -- Gabriel Genellina From jeff at schwabcenter.com Sat Feb 9 21:31:46 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Sat, 09 Feb 2008 18:31:46 -0800 Subject: Is there an easy way to sort a list by two criteria? In-Reply-To: <902c5105-c85d-4ba5-8c9f-0dd5061cef9e@b2g2000hsg.googlegroups.com> References: <902c5105-c85d-4ba5-8c9f-0dd5061cef9e@b2g2000hsg.googlegroups.com> Message-ID: neocortex wrote: > Hello! > I am a newbie in Python. Recently, I get stuck with the problem of > sorting by two criteria. In brief, I have a two-dimensional list (for > a table or a matrix). Now, I need to sort by two columns, but I cannot > figure out how to do that. I read somewhere that it is possible to do: >>>> table.sort().sort() > but it does not work. > Can anyone help me with this? > PS: I am using Python under Ubuntu 6.06. You can specify an arbitrary comparison function with the cmp key to sort. IOW, use table.sort(cmp=f), where f is defined to compare table entries (rows?) by whichever criteria are required. From stefan_ml at behnel.de Thu Feb 7 10:52:57 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 07 Feb 2008 16:52:57 +0100 Subject: Why not a Python compiler? In-Reply-To: References: Message-ID: <47AB2959.6030705@behnel.de> Jean-Paul Calderone wrote: > On Thu, 07 Feb 2008 11:03:12 +0100, Stefan Behnel > wrote: >> Take a look at Cython. It's an optimising Python-to-C compiler for >> writing >> Python extensions. So you can basically take a Python module and >> compile it to >> C code that runs against the CPython runtime. >> >> http://cython.org/ > > It's a not-quite-Python-to-C compiler. Ok, there are differences. For example, you can't define functions dynamically (it doesn't currently support closures anyway). But it already supports a much wider subset of the language than Pyrex originally did. For example, you can use list comprehensions and Python 3 keyword-only arguments in function signatures. I would expect it would compile quite a lot of Python code out there without or with only minor modifications. > I don't think it is an optimizing > compiler either. Can you provide a reference for this? It optimises a lot of common patterns into very fast sequences of Python API calls (or even generates specialised non-API code for them). It also generates optimised runtime code for special cases based on the type of an object (e.g. if the object you iterate turns out to be a list, it uses fast list API calls in loops, and a standard iterator otherwise). So the generated code is usually much faster than what Pyrex gives you. Robert and I had an optimise session lately where we dropped the function call-overhead by some 20-50% (!) compared to the preceding Cython version (not even to Pyrex), just depending on the signature. I think that qualifies for an "optimising" compiler. Stefan From george.sakkis at gmail.com Fri Feb 29 22:28:45 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 29 Feb 2008 19:28:45 -0800 (PST) Subject: convert string number to real number - ValueError: invalid literal for int() with base 10: '"2"' References: <3ca86e1d-a32f-48f2-bc9a-6cb792c0c631@z17g2000hsg.googlegroups.com> Message-ID: On Feb 28, 5:56 pm, davidj411 wrote: > i am parsing a cell phone bill to get a list of all numbers and the > total talktime spend on each number. > > (snipped) > > I actually found a good solution. > (snipped) If you post 1-2 samples of the cell phone bill input, I am sure you'll get much better solutions in terms of clarity, simplicity and elegance, commonly known as "pythonicity" :) George From tkirke at gmail.com Sat Feb 23 18:55:25 2008 From: tkirke at gmail.com (tkirke at gmail.com) Date: Sat, 23 Feb 2008 15:55:25 -0800 (PST) Subject: looking for open source simulink clone in python Message-ID: <125fdf2a-65e5-4085-b057-4f92f935953f@h11g2000prf.googlegroups.com> Does anyone know of something like this? I've searched to no avail. GNUradio companion is promising but tied to gnuradio. From bignose+hates-spam at benfinney.id.au Thu Feb 7 23:09:56 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 08 Feb 2008 15:09:56 +1100 Subject: brain stuck. whats occurring here? References: Message-ID: <8763x09jhn.fsf@benfinney.id.au> "Mark Tolonen" writes: > wrote: > > I'm after > > [[[],[],[],[],[]],[[],[],[],[],[]],[[],[],[],[],[]],[[],[],[],[],[]],[[],[],[],[],[]]] > > How about: > > >>> [[[]]*5]*5 > [[[], [], [], [], []], [[], [], [], [], []], [[], [], [], [], []], > [[], [], [], [], []], [[], [], [], [], []]] Not too useful. >>> foo = [[[]] * 5] * 5 >>> foo [[[], [], [], [], []], [[], [], [], [], []], [[], [], [], [], []], [[], [], [], [], []], [[], [], [], [], []]] >>> foo[0][0].append("spam") >>> foo [[['spam'], ['spam'], ['spam'], ['spam'], ['spam']], [['spam'], ['spam'], ['spam'], ['spam'], ['spam']], [['spam'], ['spam'], ['spam'], ['spam'], ['spam']], [['spam'], ['spam'], ['spam'], ['spam'], ['spam']], [['spam'], ['spam'], ['spam'], ['spam'], ['spam']]] As made clear in the rest of the thread, the OP wants every one of those lists to be different objects. -- \ "To me, boxing is like a ballet, except there's no music, no | `\ choreography, and the dancers hit each other." ?Jack Handey | _o__) | Ben Finney From max at alcyone.com Mon Feb 18 15:05:55 2008 From: max at alcyone.com (Erik Max Francis) Date: Mon, 18 Feb 2008 12:05:55 -0800 Subject: Seemingly odd 'is' comparison. In-Reply-To: <47b36135$0$26076$88260bb3@free.teranews.com> References: <47b36135$0$26076$88260bb3@free.teranews.com> Message-ID: Tobiah wrote: >>>> print float(3.0) is float(3.0) > True >>>> print float(3.0 * 1.0) is float(3.0) > False >>>> It's implementation dependent what values these expressions will take. If you're trying to test equality, use `==`, not `is`. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis There is nothing more incomprehensible than a wrangle among astronomers. -- H.L. Mencken From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Feb 3 07:34:34 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 03 Feb 2008 13:34:34 +0100 Subject: Is it explicitly specified? References: Message-ID: <60lqmqF1rkeiqU1@mid.individual.net> mario ruggier wrote: > It may sometimes be useful to make use of the conceptual > difference between these two cases, that is that in one case the > user did not specify any key and in the other the user explicitly > specified the key to be None. Do you have an example where this might be useful? > Is there any way to tell this difference from within the called > function? And if so, would there be any strong reasons to not rely > on this difference? IMHO, it's "magic". > Would it be maybe a little abusive of what a keyword arg actually > is? No, but you'd have to explain to users why it behaves like this. I wouldn't expect this behaviour. If the function signature says the default value for "key" is None, I expect it to behave the same no matter if I leave out "key" or if I set it explicitly. Regards, Bj?rn -- BOFH excuse #307: emissions from GSM-phones From arnodel at googlemail.com Fri Feb 1 16:13:59 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 1 Feb 2008 13:13:59 -0800 (PST) Subject: How to identify which numbers in a list are within each others' range References: <6b4ac79b-6267-438d-8b28-aa4bba78a586@i3g2000hsf.googlegroups.com> <1ffed8a2-f00b-4913-802f-b2cc9fa0ab19@i12g2000prf.googlegroups.com> <073ebb96-3572-4aa5-88d6-53e97cc55633@c4g2000hsg.googlegroups.com> <406cdd9f-07be-4967-8a4b-83fb246e3f92@v4g2000hsf.googlegroups.com> Message-ID: On Feb 1, 8:34?pm, "Neil Cerutti" wrote: > On Feb 1, 2008 3:16 PM, Arnaud Delobelle wrote: > > The total number of iterations is 1+2+...+n = n(n+1)/2 (when n is the > > number of intervals) so this has quadratic behaviour regardless of > > input.[...] > But it breaks out of the inner loop as soon as ranges on the right > cannot overlap. The loop is O(N) for all input if I define N as > "number of overlaps", a pretty reasonable definition--it's madness to > expect to report N overlaps with less than N complexity. > > Unless I'm making a silly mistake. Again. No you're not mistaken, I am. I didn't see the 'else: break' bit which of course makes all the difference. Sorry... On the point of complexity though, it is only O(N) is N dominates nlogn (n being the length of input). -- Arnaud From ebgssth at gmail.com Wed Feb 6 07:39:23 2008 From: ebgssth at gmail.com (js) Date: Wed, 6 Feb 2008 21:39:23 +0900 Subject: TheSchwartz in Python? Message-ID: Hi, I'm looking for a job queue manager in Python, like TheSchwartz.[1]. I found there's TheSchawrtz server, RPC server powered by Gearman, to which Python/Ruby can connect [2], but setting up two languages env is a little cumbersome to me. Is there any alternative to that in Python? The requirement is * Store job queue in disk, not memory * Easy to set up * 100% Python Any pointers would be appliciated. Thanks. [1] http://search.cpan.org/~bradfitz/TheSchwartz-1.04/lib/TheSchwartz.pm [2] http://brad.livejournal.com/2332359.html From byte8bits at gmail.com Wed Feb 13 16:11:01 2008 From: byte8bits at gmail.com (brad) Date: Wed, 13 Feb 2008 16:11:01 -0500 Subject: Email Directly from python In-Reply-To: <47b35ab7$0$8718$e4fe514c@dreader24.news.xs4all.nl> References: <47b35ab7$0$8718$e4fe514c@dreader24.news.xs4all.nl> Message-ID: Martin P. Hellwig wrote: > The tricky part is how to resolve the mail server for a mail address. > Usually you have to query the mx record of that domain. I solved that by > looking if I can find the nslookup binary. The from and to are static constants... they don't change. Mail just seems so tricky these days what with all the blacklists, greylists, whitelists, etc. It's almost as if email is broken. Location of the sending pc matters too. Just wondering if there is a super simple one liner in Python (that's portable) that can do this. From robert.rawlins at thinkbluemedia.co.uk Sun Feb 17 10:20:29 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Sun, 17 Feb 2008 15:20:29 -0000 Subject: Memory Issue Message-ID: <000401c87178$a66d8a30$f3489e90$@rawlins@thinkbluemedia.co.uk> Afternoon Guys, I've got what I would consider to be a strange memory leak within an application I've been working on. When the application is running the consumed system memory creeps up slowly, getting higher and higher. However, when looking at 'top' to display the memory allocation for all the applications, the actual assigned memory to the 'python' process doesn't appear to change, it consistently looks like: 2414 root 20 0 9516 6316 3148 S 0.0 2.5 0:03.62 python However the currently used memory for the entire system, shown here: Mem: 256760k total, 35588k used, 221172k free, 2096k buffers Continues to escalate until the system runs out of memory. I can be pretty sure that this is something to do with my application as whenever the app isn't running then the memory usage doesn't increase. An additional strangeness to this is that when my application is killed, the memory doesn't drop back down again? Is that normal? My understanding of a memory leak was that when the application dies the memory will be freed back up again. Can any offer any suggestions as to what is causing this problem? Is it perhaps not my actual application but something I'm calling from within it? Cheers, Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From kwa at kuwata-lab.com Tue Feb 26 18:26:18 2008 From: kwa at kuwata-lab.com (makoto kuwata) Date: Tue, 26 Feb 2008 15:26:18 -0800 (PST) Subject: Question about PyPI and 'easy_install' References: <700d4ba3-e088-4c7d-a4d8-96b68dccb61e@71g2000hse.googlegroups.com> Message-ID: <259e1145-b99a-4f85-bccc-debbdaca33cd@n77g2000hse.googlegroups.com> On 2008-02-26, Vsevolod Balashov wrote: > > I`m think this patch is helpful for you > > ---BEGIN PATCH--- > > --- setup.py.orig ? ? ? 2007-10-23 03:54:18.000000000 +0400 > +++ setup.py ? ?2008-02-26 14:08:44.660000000 +0300 > @@ -6,12 +6,10 @@ > > ?import sys, re > -if len(sys.argv) > 1 and sys.argv[1] == 'egg_info': > - ? ?from ez_setup import use_setuptools > - ? ?use_setuptools() > -from distutils.core import setup > +from ez_setup import use_setuptools > +from setuptools import setup > > -name ? ? = 'pyTenjin' > +name ? ? = 'Tenjin' > ?version ?= '0.6.1' > ?author ? = 'makoto kuwata' > ?email ? ?= '... at kuwata-lab.com' > > ---END PATCH--- Thank you, Vsevolod. Your patch shows that both project name (Tenjin) and package name (pyTenjin) should be the same name. And, I'm afraid that your patch seems to require user to install setuptools. I want Tenjin to be install not only with easy_install but also without setuptools. -- regards, makoto kuwata From kay.schluehr at gmx.net Sun Feb 3 18:38:24 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sun, 3 Feb 2008 15:38:24 -0800 (PST) Subject: Python feature request : operator for function composition References: <33b9a229-779f-4951-8c71-6e9e0252fa5a@h11g2000prf.googlegroups.com> Message-ID: On Feb 3, 11:34 pm, George Sakkis wrote: > On Feb 3, 12:09 am, Kay Schluehr wrote: > > > As you know, there is no operator for function composition in Python. > > When you have two functions F and G and want to express the > > composition F o G you have to create a new closure > > > lambda *args, **kwd: F (G (*args, **kwd)) > > > or you write a composition in functional style > > > compose( F, G ) > > > None of these solutions is particular terse. > > What if F takes more than one (positional and/or keyword) arguments? > How common is this special use case where F takes a single argument > (the result of G) to deserve a special operator ? > > George O.K. Point taken. Here is a more general form of compose that is applicable when both F and G take *args and **kwd arguments. def compose(F,G): def prepare_args(args, kwd = {}): return args if isinstance(args, tuple) else (args,), kwd def apply_composition(*args, **kwd): nargs, nkwd = prepare_args(G(*args, **kwd)) return F(*nargs, **nkwd) return apply_composition From steve at REMOVE-THIS-cybersource.com.au Fri Feb 1 18:41:24 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 01 Feb 2008 23:41:24 -0000 Subject: very simple Genetic Algorithm completed References: <674f29dc-7374-4125-9a5f-adc2bfbce16f@k39g2000hsf.googlegroups.com> Message-ID: <13q7bh4fkfvo525@corp.supernews.com> On Fri, 01 Feb 2008 06:09:49 -0800, Paul McGuire wrote: > IIRC, the optimization of successive string concatentions is only > available when running Python on Windows. If you are running on Linux, > this should have more benefit.) There's no reason to believe it is platform-dependent, although it is implementation-dependent (only works in CPython). It was introduced in Python 2.4: http://www.python.org/doc/2.4/whatsnew/node12.html -- Steven From bj_666 at gmx.net Fri Feb 8 20:15:41 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 9 Feb 2008 01:15:41 GMT Subject: Why not a Python compiler? References: <28eead2f-a40c-414b-bd3d-a941f8a851a2@d70g2000hsb.googlegroups.com> <81339c25-f9b6-47a1-941e-8ae39c35773c@e6g2000prf.googlegroups.com> <98a1bc2d-290b-4b6d-8a3d-eda7666d2b8b@l1g2000hsa.googlegroups.com> <13qmtu5j1b1p6a2@corp.supernews.com> <8763x0fix1.fsf@mulj.homelinux.net> <13qp5a02t36def9@corp.supernews.com> Message-ID: <614d5tF1tprtrU2@mid.uni-berlin.de> On Fri, 08 Feb 2008 17:45:36 +0000, Grant Edwards wrote: > On 2008-02-08, Arnaud Delobelle wrote: > >> Please get back on topic. This discussion is about parsecs and >> wookies now. > > What's a "wookie" a unit of? The degree of confusion among the jury when using the Chewbacca defense. :-) http://en.wikipedia.org/wiki/Chewbacca_defense Ciao, Marc 'BlackJack' Rintsch From john106henry at hotmail.com Tue Feb 19 00:15:02 2008 From: john106henry at hotmail.com (John Henry) Date: Mon, 18 Feb 2008 21:15:02 -0800 (PST) Subject: pyinstall and matplotlib References: <254161cb-f927-4659-b1a5-c34b5c2953ac@s8g2000prg.googlegroups.com> <3144e444-3542-4550-a280-ff15da8bed0b@l16g2000hsh.googlegroups.com> <9d85cb45-2e62-4c4a-9d31-35e5cb9ef3ea@1g2000hsl.googlegroups.com> <8c7faf23-31d4-4846-ae05-f59479fe6775@s12g2000prg.googlegroups.com> <7f752cd6-6914-4e6b-a559-f2b66959c1b2@s12g2000prg.googlegroups.com> Message-ID: <1ab894fc-d5f8-4a02-ae55-13ee35087c20@d4g2000prg.googlegroups.com> On Feb 18, 8:04 pm, John Henry wrote: > On Feb 18, 7:34 pm, John Henry wrote: > > > > > On Feb 17, 11:50 am, Stef Mientki wrote: > > > > hi John, > > > > John Henry wrote: > > > > Anybody willing to help? > > > > I struggled the past few days with the same problem, > > > and with the help of Werner Bruhin (wxPython list) I found a solution. > > > I had 2 problems: > > > - not finding mpl datapath > > > - matplotlib insisted on installing backends that were distorted on my > > > system > > > > The first problem was solved with the following script: > > > it has some special parts > > > - remove the distro and build directories before running setup > > > - a special matplot part, ensuring mpl-data is copied and installed > > > - a lot of excludes for matplotlib ( which doesn't seem to work :-( ) > > > > Kill_Distro = True > > > MatPlotLib_Wanted = True > > > > from distutils.core import setup > > > import py2exe > > > import sys > > > subdirs = [ '..\\P24_support', '..\\P24_pictures', > > > '..\\P24_Lib_Extensions' ] > > > for subdir in subdirs: > > > if not ( subdir in sys.path) : sys.path.append ( subdir ) > > > > from file_support import * > > > > import shutil > > > import glob > > > > # *********************************************************************** > > > # Some suggests that old build/dist should be cleared > > > # *********************************************************************** > > > dist_paths = [ 'D:\\Data_Python\\P24_PyLab_Works\\build', > > > 'D:\\Data_Python\\P24_PyLab_Works\\dist' ] > > > for path in dist_paths : > > > if File_Exists ( path ) : > > > shutil.rmtree ( path ) > > > # *********************************************************************** > > > > # *********************************************************************** > > > # *********************************************************************** > > > data_files = [] > > > packages = [] > > > includes = [] > > > excludes = [] > > > dll_excludes = [] > > > data_files.append ( ( '', glob.glob ( 'templates_*.*' ) ) ) > > > > # *********************************************************************** > > > # For MatPlotLib > > > # *********************************************************************** > > > if MatPlotLib_Wanted : > > > import matplotlib > > > > includes.append ( 'matplotlib.numerix.random_array' ) > > > > packages.append ( 'matplotlib' ) > > > packages.append ( 'pytz' ) > > > > data_files.append ( ( r'mpl-data', glob.glob ( > > > r'P:\\Python\\Lib\\site-packages\\matplotlib\\mpl-data\\*.*' ))) > > > data_files.append ( ( r'mpl-data', glob.glob ( > > > > r'P:\\Python\\Lib\\site-packages\\matplotlib\\mpl-data\\matplotlibrc' ))) > > > data_files.append ( ( r'mpl-data\\images', glob.glob ( > > > r'P:\\Python\\Lib\\site-packages\\matplotlib\\mpl-data\\images\\*.*' ))) > > > data_files.append ( ( r'mpl-data\\fonts\\afm', glob.glob ( > > > > r'P:\\Python\\Lib\\site-packages\\matplotlib\\mpl-data\\fonts\\afm\\*.*' ))) > > > data_files.append ( ( r'mpl-data\\fonts\\pdfcorefonts', glob.glob ( > > > > r'P:\\Python\\Lib\\site-packages\\matplotlib\\mpl-data\\fonts\\pdfcorefonts\\*.*' > > > ))) > > > data_files.append ( ( r'mpl-data\\fonts\\ttf', glob.glob ( > > > > r'P:\\Python\\Lib\\site-packages\\matplotlib\\mpl-data\\fonts\\ttf\\*.*' ))) > > > > excludes.append ( '_gtkagg') > > > excludes.append ( '_tkagg' ) > > > excludes.append ( '_agg2' ) > > > excludes.append ( '_cairo' ) > > > excludes.append ( '_cocoaagg' ) > > > excludes.append ( '_fltkagg' ) > > > excludes.append ( '_gtk' ) > > > excludes.append ( '_gtkcairo') > > > excludes.append ( 'backend_qt' ) > > > excludes.append ( 'backend_qt4') > > > excludes.append ( 'backend_qt4agg' ) > > > excludes.append ( 'backend_qtagg' ) > > > excludes.append ( 'backend_cairo' ) > > > excludes.append ( 'backend_cocoaagg' ) > > > excludes.append ( 'Tkconstants' ) > > > excludes.append ( 'Tkinter' ) > > > excludes.append ( 'tcl' ) > > > excludes.append ( "_imagingtk" ) > > > excludes.append ( "PIL._imagingtk" ) > > > excludes.append ( "ImageTk" ) > > > excludes.append ( "PIL.ImageTk" ) > > > excludes.append ( "FixTk" ) > > > > dll_excludes.append ( 'libgdk-win32-2.0-0.dll' ) > > > dll_excludes.append ( 'libgdk_pixbuf-2.0-0.dll' ) > > > dll_excludes.append ( 'libgobject-2.0-0.dll') > > > dll_excludes.append ( 'tcl84.dll' ) > > > dll_excludes.append ( 'tk84.dll' ) > > > dll_excludes.append ( 'tclpip84.dll' ) > > > # *********************************************************************** > > > > # seems not to be found (imported in brick.py) > > > includes.append ( 'PyLab_Works_properties' ) > > > > # *********************************************************************** > > > # *********************************************************************** > > > > # If run without args, build executables, in quiet mode. > > > if len(sys.argv) == 1: > > > sys.argv.append("py2exe") > > > > setup ( > > > windows = ['PyLab_Works.py'] , > > > options = { > > > 'py2exe' : { > > > 'includes' : includes, > > > 'excludes' : excludes, > > > 'dll_excludes' : dll_excludes, > > > 'packages' : packages, > > > }}, > > > data_files = data_files > > > ) > > > > import subprocess > > > result = subprocess.call ( > > > [ 'P:\Program Files\Inno Setup 4\ISCC.exe', > > > 'D:\Data_Python\P24_PyLab_Works\PyLab_Works.iss']) > > > > if (result==0) and Kill_Distro : > > > for path in dist_paths : > > > if File_Exists ( path ) : > > > shutil.rmtree ( path ) > > > > Th? essential issue is not to use pylab to do the imports for you, > > > but perform your own imports, > > > this might be a lot of work: in my case the import looks like this > > > (I don't include numerix, because I use numpy), > > > so in my program to distribute, I use this : > > > > import matplotlib > > > matplotlib.use('WXAgg') > > > from matplotlib.backends.backend_wxagg \ > > > import Toolbar, FigureManager > > > from matplotlib.backends.backend_wxagg \ > > > import FigureCanvasWxAgg as FigureCanvas > > > from matplotlib import rcParams, mlab, cm > > > from matplotlib.mlab import meshgrid > > > from matplotlib.figure import Figure > > > from matplotlib.axes import Subplot > > > > hope this might help you somewhat, > > > cheers, > > > Stef > > > Steve, > > > Thanks for your help. > > > Using your code as a starter, I've gone a lot further. I have now > > gone pass the point where matplotlib was unable to find its > > datafiles. However, the program now stops because it can't get > > Tkinter started. The error message in the log says: > > > Traceback (most recent call last): > > File "multicolor.py", line 11, in ? > > File "pylab.pyc", line 1, in ? > > File "matplotlib\pylab.pyc", line 222, in ? > > File "matplotlib\backends\__init__.pyc", line 24, in pylab_setup > > File "matplotlib\backends\backend_tkagg.pyc", line 7, in ? > > ImportError: No module named Tkinter > > > Any ideas? > > > Thanks, > > BTW: I don't use Tkinter for GUI, I use PythonCard and wxPython. May > be the Tkinter is invoked by the multicolor.py sample? I tried another application which I know for sure doesn't use Tkinter and yet it still tries to invoke Tkinter. So, I need to disable the backend_tkagg.pyc somehow. Any suggestions? Thanks, From grante at visi.com Wed Feb 27 16:41:24 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 27 Feb 2008 21:41:24 -0000 Subject: Raising exception on STDIN read References: <62lh86F22rcf3U1@mid.uni-berlin.de> <13sblr3dl3fh7f8@corp.supernews.com> Message-ID: <13sbm84f80ub0a5@corp.supernews.com> On 2008-02-27, Grant Edwards wrote: > On 2008-02-27, Michael Goerz wrote: >> Hi, >> >> I would like to raise an exception any time a subprocess tries to read >> from STDIN: >> >> latexprocess = subprocess.Popen( \ >> 'pdflatex' + " " \ >> + 'test' + " 2>&1", \ >> shell=True, \ >> cwd=os.getcwd(), \ >> env=os.environ, \ >> stdin=StdinCatcher() # any ideas here? >> ) >> >> An exception should be raised whenever the pdflatex process >> reads from STDIN... and I have no idea how to do it. Any suggestions? > > If I were you, I'd just run LaTeX in batch mode. That's what I > always used to do when automating the running of LaTeX using a > shell script or makefile. IIRC, you do something like this: > > ret = os.system("latex \\batchmode\\input %s" % filename) > > The return status will be zero for success and non-zero if > there were any errors. Ooops. Just did a quick test, and you need to double up the backslashes one more time when using os.system(). I think there might also be a way to supress the chatter coming out of TeX, but if you're using subprocess, you can just attach stdout and stderr to a bitbucket. Here's a demo where label1.tex has no errors and label2.tex has an error: ________________________testit.py____________________________________ import os ret1 = os.system('latex \\\\batchmode\\\\input %s' % 'label1.tex') print ret1 ret2 = os.system('latex \\\\batchmode\\\\input %s' % 'label2.tex') print ret2 _____________________________________________________________________ $ python testit.py This is pdfeTeX, Version 3.141592-1.30.5-2.2 (Web2C 7.5.5) entering extended mode LaTeX2e <2003/12/01> Babel and hyphenation patterns for american, french, german, ngerman, b ahasa, basque, bulgarian, catalan, croatian, czech, danish, dutch, esperanto, e stonian, finnish, greek, icelandic, irish, italian, latin, magyar, norsk, polis h, portuges, romanian, russian, serbian, slovak, slovene, spanish, swedish, tur kish, ukrainian, nohyphenation, loaded. 0 This is pdfeTeX, Version 3.141592-1.30.5-2.2 (Web2C 7.5.5) entering extended mode LaTeX2e <2003/12/01> Babel and hyphenation patterns for american, french, german, ngerman, b ahasa, basque, bulgarian, catalan, croatian, czech, danish, dutch, esperanto, e stonian, finnish, greek, icelandic, irish, italian, latin, magyar, norsk, polis h, portuges, romanian, russian, serbian, slovak, slovene, spanish, swedish, tur kish, ukrainian, nohyphenation, loaded. 256 -- Grant Edwards grante Yow! Somewhere in DOWNTOWN at BURBANK a prostitute is visi.com OVERCOOKING a LAMB CHOP!! From ilias at lazaridis.com Mon Feb 18 05:59:10 2008 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Mon, 18 Feb 2008 02:59:10 -0800 (PST) Subject: TRAC - Trac, Project Leads, Python, and Mr. Noah Kantrowitz (sanitizer) References: <3d40196b-b1c8-4e18-92f0-7ce5a5a38853@u72g2000hsf.googlegroups.com> Message-ID: [RESEND answer to all initial groups] On 16 ???, 19:15, Jeff Schwab wrote: > Ilias Lazaridis wrote: > > Essence: > Spam spam spam spam... > I just looked at your resume. http://lazaridis.com/resumes/lazaridis.html (need to update it, lot's of irrelevant stuff, should focus on my failures) > What is Abstract Project Management? I've mentioned "abstract _product_ management" Don't know exactly, I've never tried to articulate the meaning which I've internally. You could extract the meaning from "Abstract Base Class" or "Abstractness" in general. Something like "universal product management". Or managing a product without having many specific information about it. Something like this _possibly_: http://case.lazaridis.com/wiki/KomodoAudit From huayang.xia at gmail.com Wed Feb 6 17:33:54 2008 From: huayang.xia at gmail.com (Huayang Xia) Date: Wed, 6 Feb 2008 14:33:54 -0800 (PST) Subject: Is there a way to use .NET DLL from Python References: <85706ba0-8c24-4324-9a79-98c97fc802db@e4g2000hsg.googlegroups.com> <6c2845aa-aec5-4b75-852a-551b9cd1d6ab@f10g2000hsf.googlegroups.com> Message-ID: <949f6889-934d-4e93-b9d5-96d6d5945333@s37g2000prg.googlegroups.com> Or maybe we can do it in IronPython? From darcy at druid.net Tue Feb 26 08:44:48 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 26 Feb 2008 08:44:48 -0500 Subject: Odd behaviour of *.pth files and Apache In-Reply-To: References: <20080221135525.e4f59094.darcy@druid.net> <20080223095245.7c6af2e1.darcy@druid.net> Message-ID: <20080226084448.3cef65f2.darcy@druid.net> On Tue, 26 Feb 2008 03:01:33 -0200 "Gabriel Genellina" wrote: > En Sat, 23 Feb 2008 12:52:45 -0200, D'Arcy J.M. Cain > escribi?: > > I have more information now. It seems that it recurses the .pth files > > it finds in PYTHONPATH but not for directories found in the .pth files > > in site-packages. Is this expected behaviour? The documentation > > suggests that it should pick up both. > > If a .pth file contains a valid directory, it is added to sys.path but > it's not searched for additional .pth files. From > http://docs.python.org/lib/module-site.html > > "A path configuration file is a file whose name has the form package.pth > AND EXISTS IN ONE OF THE FOUR DIRECTORIES MENTIONED ABOVE" (emphasis by me) > > (the four directories being .../lib/python2.5/site-packages, site-python, > etc.) > > (Mmm, what the 2.5 docs say is not exactly the same as the actual code in > site.py, and the version in http://docs.python.org/dev/library/site.html > is not the same as the svn version of site.py... anyway, directories added > by mean of .pth files are not recursively searched for more .pth files) But that is not true. If I add a path by setting PYTHONPATH and there is a .pth in that directory then it is read and recursively searched for more .pth files. It is only when the path is added because it is in site-packages that it doesn't load the .pth files found. In http://www.python.org/doc/inst/search-path.html there is more specific language: "The most convenient way is to add a path configuration file to a directory that's already on Python's path, usually to the .../site-packages/ directory. Path configuration files have an extension of .pth, and each line must contain a single path that will be appended to sys.path. (Because the new paths are appended to sys.path, modules in the added directories will not override standard modules. This means you can't use this mechanism for installing fixed versions of standard modules.) "Paths can be absolute or relative, in which case they're relative to the directory containing the .pth file. Any directories added to the search path will be scanned in turn for .pth files. See site module documentation for more information." Directories listed in .pth files in site-packages are "added to the search path" so they should be scanned for more .pth files. This really smells like a bug in either the code or the docs. I hope it is in the code and will eventually be fixed. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From mensanator at aol.com Sun Feb 24 19:08:53 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 24 Feb 2008 16:08:53 -0800 (PST) Subject: How about adding rational fraction to Python? References: <70ecaf16-7308-455f-9048-730b2b2f9f2f@p43g2000hsc.googlegroups.com> <13rf9tvbkt66r2a@corp.supernews.com> <198927a7-9478-42b3-a972-82049f0130ac@u10g2000prn.googlegroups.com> <1bc9bba7-dc7f-4cfe-8e1c-fa5901c9f556@n77g2000hse.googlegroups.com> <97f30679-483d-4751-9a6e-0858b36eb426@d4g2000prg.googlegroups.com> <649ac8a9-ae09-4e9b-85c2-f37043af21fd@28g2000hsw.googlegroups.com> <13s3smnkp06arcd@corp.supernews.com> Message-ID: On Feb 24, 4:42?pm, Steven D'Aprano wrote: > On Sun, 24 Feb 2008 12:19:53 -0800, Mensanator wrote: > > Out of curiosity, of what use is denominator limits? > > > The problems where I've had to use rationals have never afforded me such > > luxury, so I don't see what your point is. > > It ensures that your fraction's denominator doesn't grow indefinitely, at > the cost of some precision. In principle, fraction denominators can grow > exponentially. In practice, probably less quickly, but still quickly > enough that people on this list have reported that adding two fractions > lead to millions of digits in each denominator and massive paging as > their computer struggled to perform the addition. Ok, but I've never seen that happen with the rationals of the gmpy module. I'm getting the feeling that this fear of rationals is overrated. But maybe it's because I know what I'm doing. Naw, that can't be it. > > The beauty of fractions is that they give you infinite precision. The > danger of fractions is that it takes a lot of memory to store infinitely > precise numbers :) > > Frankly, I think that for most real-world data, it's unlikely to be a > problem, My guess is that you're right. > but Guido's experiences with ABC were the opposite. But then we > don't know how naive the ABC fraction libraries were. For all I know they > did this: > > 1/2 + 1/2 = 4/4 > 4/4 - 1/2 = 4/8 > 4/8 + 1/2 = 16/16 > etc. Perhaps Guido should have an occasional peek at the monster he's created. The gmpy library always reduces to lowest denominator, so the above couldn't happen. > > -- > Steven From david.car7 at gmail.com Tue Feb 5 22:04:48 2008 From: david.car7 at gmail.com (david.car7 at gmail.com) Date: Tue, 5 Feb 2008 19:04:48 -0800 (PST) Subject: Using a class as a structure/container References: <31f9058a-60a9-47b5-9c05-bddb31d2d04c@u10g2000prn.googlegroups.com> Message-ID: <0e647511-90bc-4648-960e-96936bfaf218@h11g2000prf.googlegroups.com> On Feb 5, 9:59?pm, david.c... at gmail.com wrote: > Is it appropriate to use a class as a simple container in order to > access attributes using a series of dot operators? ?Is their a more > Pythonic way of doing this? ?For instance, I have a "container" class > which is never instantiated directly, but only through another class. > Access to certain attributes would be something like: > > ? main_class.a.b.x > > where row and v1 are instances of the container class which are > instantianted by main_class. ?I know I can use dictionaries, but this > syntax is a little clearer as long as the number of dot operators is > not too lengthy. ?Some code would be something like: > > class container(object): > ? ? def __init__(self): > ? ? ? ? pass > > class main_class(object): > ? ? def __init__(self): > ? ? ? ? self.a = container() > ? ? ? ? settatr(self.a, 'b', container()) > ? ? ? ? settatr(self.a.b, 'x', 2) > > Thanks in advance. Oops. I meant "where a and b are instances..." instead of "where row and v1 are instances..." above. Sorry for the confusion. From luismgz at gmail.com Wed Feb 6 21:26:15 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M._Gonz=E1lez?=) Date: Wed, 6 Feb 2008 18:26:15 -0800 (PST) Subject: Is there a way to use .NET DLL from Python References: <85706ba0-8c24-4324-9a79-98c97fc802db@e4g2000hsg.googlegroups.com> <6c2845aa-aec5-4b75-852a-551b9cd1d6ab@f10g2000hsf.googlegroups.com> Message-ID: <5845a12f-41dd-4bb3-8684-483e93f55c5f@e25g2000prg.googlegroups.com> On 6 feb, 21:17, Fuzzyman wrote: > On Feb 6, 9:59 pm, "Luis M. Gonz?lez" wrote: > > > On Feb 6, 6:27 pm, Huayang Xia wrote: > > > > Hello All, > > > > I have several .NET DLL (I have no source code for them), is there > > > anyway to use them from python instead of from C#. > > > > Thanks, > > > Huayang > > > I used to put my .dll files into the .DLL folder, so I could simply > > import them as I would with any other python module. > > But since I started using Ironpython 2.0 Alpha* this doesn't work > > anymore... > > Any hint? > > The rule is probably still that the DLLs must be in a directory on > sys.path for the interpreter to find them. Try adding the directory > containing the assemblies to sys.path and see if you can add > references to them. > > Michael Foordhttp://www.manning.com/foord > > > > > Luis I tried adding the directory to sys.path. Still not working... >>> import sys >>> sys.path.append('C:\Documents and Settings\luismg\Escritorio\IronPython-2.0A 8\DLLs') >>> from ClassLibrary1 import * Traceback (most recent call last): File , line unknown, in ##235 File , line unknown, in _stub_##2 ImportError: No module named ClassLibrary1 From duncan.booth at invalid.invalid Mon Feb 18 07:31:05 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 18 Feb 2008 12:31:05 GMT Subject: Seemingly odd 'is' comparison. References: <47b36135$0$26076$88260bb3@free.teranews.com> Message-ID: Tobiah wrote: > Subject: Seemingly odd 'is' comparison. Please put your question into the body of the message, not just the headers. >>>> print float(3.0) is float(3.0) > True >>>> print float(3.0 * 1.0) is float(3.0) > False >>>> > > > Thanks, > > Tobiah > Your values are already all floats so float() just returns its arguments. In other words you can omit it: >>> 3.0 is 3.0 True >>> 3.0 * 1.0 is 3.0 False 3.0 used twice in the same compilation unit is the same constant value used twice. 3.0 * 1.0 creates a new float value. Compare with: >>> n = 3.0 >>> n is 3.0 False Here two separate compilations result in two separate values. In general any immutable results of calculations which are the same may or may not share the same object and this can vary according to the version of Python or the phase of the moon. Only use 'is' when you actually care about object identity, don't use it for a shorthand for '=='. From fetchinson at googlemail.com Sun Feb 3 14:10:55 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sun, 3 Feb 2008 11:10:55 -0800 Subject: GUI definition for web and desktop In-Reply-To: References: Message-ID: > > It's clear to me that the logic behind a web interface and a desktop > > interface are two totally different things. I don't want a magic > > method to convert an html/javascript based web app to a desktop app as > > this is clearly impossible. > > But it is not impossible to embed a server on your desktop and make it > render HTML on some windows. That's true, that is why I'm looking for a format that is html/javascript/desktop/guitoolkit agnostic. It's ideally simply a text file listing the widgets in whatever format (xml, plain text, json, etc). And the python web app takes this file, parses it and spits out the right html/javascript while the desktop app takes the same file, parses it, and spits out GUI-toolkit specific code that renders a window with those widgets using the GUI-toolkit in question. The web app code that spits out html and the desktop app code that renders a dialog window are different and have to be maintained separately but the *definition file* can be shared. > Then you'd have to code just the web app and > the desktop would also use it... > > If Internet is a requirement, you can even render the HTML from a remote > server. The internet is assumed to be accessible so this is an interesting possibility what you mention. Which GUI toolkit would be able to do this? And so it would work in a way that the desktop app grabs an html page and renders that in a dialog window? If this was possible then maybe this would solve all my problems. Thanks, Daniel From wolf_tracks at invalid.com Tue Feb 12 15:18:20 2008 From: wolf_tracks at invalid.com (W. Watson) Date: Tue, 12 Feb 2008 20:18:20 GMT Subject: IDLE Won't Start w/o Socket Error--Win XP Message-ID: After simply trying to write a program with help(MakeQTE), a module, and having it fail with socket errors, I decided to restart IDLE, thinking I knew the cause. I'm now getting msgs like: "IDLE's subprocess didn't make connection. ... firewall may be blocking the connection." I doubt the FW connection. There's a small X warning dialog that says "Socket Error: Connection refused." Is there a way to reset IDLE? -- Wayne Watson (Nevada City, CA) Web Page: From steve at holdenweb.com Wed Feb 6 21:35:22 2008 From: steve at holdenweb.com (Steve Holden) Date: Wed, 06 Feb 2008 21:35:22 -0500 Subject: mysqldb: Rows READ or Processed In-Reply-To: <1202343305.3329.4.camel@localhost.localdomain> References: <1202343305.3329.4.camel@localhost.localdomain> Message-ID: Carsten Haese wrote: > On Wed, 2008-02-06 at 18:53 -0500, Steve Holden wrote: >> If you mean the number of (say) rows updated by a SQL UPDATE statement, >> the DB API does not provide any way to access that information > > It doesn't? Isn't that what cursor.rowcount does? > When it works, yes. Perhaps I should have said that the method provided by the DB API isn't reliably implemented (for example, on SQL Server 2000 via mx.ODBC it would use a forward cursor which had no predictive ability about its contents). The specification says: """the attribute is -1 in case no executeXXX() has been performed on the cursor or the rowcount of the last operation is not determinable by the interface. [7]""" and the footnote points out that the value is "dynamically updatable" (i.e. not reliable 100% of the time). Anyway, since the OP just wanted total row count this discussion is moot. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From imageguy1206 at gmail.com Thu Feb 21 11:33:02 2008 From: imageguy1206 at gmail.com (imageguy) Date: Thu, 21 Feb 2008 08:33:02 -0800 (PST) Subject: distutils setup - changing the location in site-packages Message-ID: <753ea727-5b49-4cd4-a790-573a1b44c1c2@s12g2000prg.googlegroups.com> I am hoping if someone can set me straight. I have created a setup script for a module, however, when running the install on my own machine, I would like to place the module in a specific site-packages directory/package. So if I start with a module in .\dev\mygreatmodule.py I want to end up with; .\lib\site-packages\mytools\mygreatmodule.py. I have the setup script working, however, when I run the install, it places the module in the root of site-packages. The following is the deatils from the script setup ( name = "mymodule", version = "0.1", description = "My modules special description", author = "me", author_email = "me at mydomain.com", py_modules = ["exceptionhandler"] ) This is for development purposes. I would like to have a development copy of some "tools", but when ready and tested "publish" them to the site-packages where they can be included in "production" code. Any guidance/suggestions would be appreciated. From grante at visi.com Fri Feb 1 15:55:07 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 01 Feb 2008 20:55:07 -0000 Subject: Why os.path.isabs("/") on Windows returns True? References: <78f4b0b0-f19c-4cae-b11c-2aae8d9258fb@d70g2000hsb.googlegroups.com> Message-ID: <13q71pb5ud97fe@corp.supernews.com> On 2008-02-01, Giampaolo Rodola' wrote: > I'm trying to solve a jython-related issue and I discovered a > different behavior affecting os.path.isabs between CPython and > Jython. [...] > Is there a reason why "/" is considered an absolute pathname > by CPython? Sure seems like a bug to me. On Unix, "/" is an absolute path. On windows, "/" is relative to the current device. -- Grant Edwards grante Yow! I hope something GOOD at came in the mail today so visi.com I have a REASON to live!! From tamim.shahriar at gmail.com Fri Feb 22 23:43:48 2008 From: tamim.shahriar at gmail.com (subeen) Date: Fri, 22 Feb 2008 20:43:48 -0800 (PST) Subject: global variables: to be or not to be References: <6e476acf-44dc-4399-8836-ac1ba1115796@s13g2000prd.googlegroups.com> Message-ID: Another way to avoid using global variables is to return more than one values from the function. Here is an example that may help you to understand it: def foo(a, b, c): a += c b += c return a, b a = 5 b = 10 c = 2 print a, b a, b = foo(a, b, c) print a, b regards, Subeen. http://love-python.blogspot.com/ On Feb 23, 9:11 am, icarus wrote: > I've read 'global variables' are bad. The ones that are defined as > 'global' inside a function/method. > > The argument that pops up every now and then is that they are hard to > keep track of. I don't know Python well enough to argue with that. > Just started learning it a few days ago, so I won't get into > philosophical questions such as "why this? Why not that?". I'll take > it as it is, just like I take 1 + 1 = 2 for granted. > > So..."global variables taste bad. Avoid them." > > But how do I get around it? How do I update and access a variable > anytime I want? Any easy-to-follow examples? Thanks in advance. From miki.tebeka at gmail.com Wed Feb 20 22:57:37 2008 From: miki.tebeka at gmail.com (Miki) Date: Wed, 20 Feb 2008 19:57:37 -0800 (PST) Subject: smtplib & gnupg References: Message-ID: <377a9ae2-e9c0-481d-8e1f-b341147bda67@s37g2000prg.googlegroups.com> Hello Bernd, > at the moment my program sends mail with smtplib. Is there a chance to > sign and/or encode/cipher this mails with GnuPG? > If yes, does anyone have some sample code? Not exactly Python, but maybe http://codesorcery.net/old/mutt/mutt-gnupg-howto might help. HTH, -- Miki http://pythonwise.blogspot.com From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Feb 19 07:56:00 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 19 Feb 2008 13:56:00 +0100 Subject: Linux/Python Issues In-Reply-To: References: Message-ID: <47bad186$0$31953$426a74cc@news.free.fr> MartinRinehart at gmail.com a ?crit : > > bruno.desthuilliers at gmail.com wrote: >> IOW: all this is assumed to be >> common *n*x knowledge. > > Both GNOME and KDE put Windows to shame. An old Windows guy, like me, > can just start using either one without needing 'common *n*x > knowledge.' Err... Ever tried to compile them from sources ?-) > Too bad the *n*x community isn't more welcoming to > outsiders. C'mon, Martin, be serious. Compiling softwares from sources requires at least some minimal 'insider' knowledge *whatever the platform*. You can't seriously hope each and every source distrib to provide newbie-oriented doc for what's obviously a power-user operation. Or do you imply that there should be Windows installations instructions explaining the concepts of window, mouse, etc ? FWIW, I haven't seen so far any source distrib of any software targeting the Windows platform that didn't assume some 'common Windows knowledge'. You label yourself as "an old Windows guy". This means you have a good knowledge of this platform. How long did it take to gain this knowledge ? More than a couple weeks, I bet ? FWIW, "a couple weeks" is the time it took me - coming from Mac then Windows - to be able to compile Python (or almost any other software) from sources on linux - and most of this time was spent solving dependancies issues badly managed by the particular distro I was using by that time, which wasn't the more standard nor documented one. So, here's the basic scheme: - download the source tarball, preferably in /usr/local/src - unpack it - cd into the unpacked source directory - *carefully* read the README, INSTALL and other relevant docs - run ./configure with the relevant options - run make - run make install Wasn't too hard, was it ?-) And before you say it: yes indeed, it assumes you know how to use the command line, navigate your filesystem, copy/move things around, unpack an archive, read a text file etc... IOW, some more 'common *n*x knowledge' that you just can't hope to avoid learning if you want to properly use a *n*x system. Sorry. From exarkun at divmod.com Thu Feb 7 06:36:24 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 7 Feb 2008 06:36:24 -0500 Subject: Why not a Python compiler? In-Reply-To: <47AAD760.5030504@behnel.de> Message-ID: <20080207113624.6859.1369913610.divmod.quotient.6226@ohm> On Thu, 07 Feb 2008 11:03:12 +0100, Stefan Behnel wrote: >Santiago Romero wrote: > [snip] >> >> Why not a Python COMPILER? >> >> It would be very nice to be able to output Linux, MAC or Windows >> binaries of compiled (not bytecompiled) code. It would run faster, it >> will be smaller in size (I think) > >Take a look at Cython. It's an optimising Python-to-C compiler for writing >Python extensions. So you can basically take a Python module and compile it to >C code that runs against the CPython runtime. > >http://cython.org/ > It's a not-quite-Python-to-C compiler. I don't think it is an optimizing compiler either. Can you provide a reference for this? Jean-Paul From deets at nospam.web.de Wed Feb 6 13:04:49 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 06 Feb 2008 19:04:49 +0100 Subject: Installing PyQt In-Reply-To: References: Message-ID: <60ub6fF1s9qriU1@mid.uni-berlin.de> Marcus Strube schrieb: > Hi > > I was trying to install PyQt, but things don't work as promised. > > I'm working on OS X 10.5, didn't install another version of Python - so > it's 2.5.1 -, installed the latest "qt-mac-opensource-4.3.3.dmg" and the > latest sip 4.7.3. But when I then try to run python configure.py for > PyQt 4.3.3 I get "Import Error: No module named sipconfig" (I also > retried after a Reboot) > > Did anybody have the same problem and can tell me what solved it?? Just a suggestion- does the DMG really install into your custom 2.5 installation? I'd gather it rather uses the pre-shipped python. Diez From bj_666 at gmx.net Tue Feb 26 09:39:13 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 26 Feb 2008 14:39:13 GMT Subject: dict.get and str.xsplit References: <98a989a2-dfcb-4da5-979a-12011d5e4f8e@i12g2000prf.googlegroups.com> <62il6uF223i2qU1@mid.uni-berlin.de> Message-ID: <62imkhF223i2qU4@mid.uni-berlin.de> On Tue, 26 Feb 2008 06:33:01 -0800, castironpi wrote: > On Feb 26, 8:14?am, Marc 'BlackJack' Rintsch wrote: >> On Tue, 26 Feb 2008 06:02:12 -0800, bearophileHUGS wrote: >> > This is a real difference, that has real impact on the programs I >> > write, so I often use the if/else approach, despite the dict.get() >> > method being semantically fitter and shorter. >> > So can the dict.get() method be speed up? And if not, why? >> >> I guess it's the method lookup that's the slow part. ?Factor it out of the >> loop and measure again:: >> >> ? ? adict_get = adict.get >> ? ? for _ in xrange(M): >> ? ? ? ? for k in keys1: >> ? ? ? ? ? ? r = adict_get(k, None) >> ? ? ? ? for k in keys2: >> ? ? ? ? ? ? r = adict_get(k, None) >> >> Ciao, >> ? ? ? ? Marc 'BlackJack' Rintsch > > Can't be. The string 'get' is only hashed once, since it's hard-coded > into the script, and looking it up can't be any slower than looking up > __getitem__. Within functions it is faster. In the original code the `get` attribute is looked up on the `adict` object twice in each loop iteration via hashing. In my code it is looked up once before the loop and within the loop the local name `adict_get` isn't looked up but hardcoded as index into the internal locals array of the function. Ciao, Marc 'BlackJack' Rintsch From certo at comeno.it Thu Feb 7 16:28:32 2008 From: certo at comeno.it (imho) Date: Thu, 07 Feb 2008 21:28:32 GMT Subject: a trick with lists ? In-Reply-To: References: <47ab3de3$0$9587$426a34cc@news.free.fr> <610tlcF1t2hegU1@mid.uni-berlin.de> Message-ID: <4KKqj.8364$FR.45391@twister1.libero.it> Steve Holden ha scritto: >>> What I do not fully understand is the line "self.tasks[:] = tasks". >>> Why does the guy who coded this did not write it as "self.tasks = >>> tasks"? What is the use of the "[:]" trick ? >> >> It changes the list in-place. If it has been given to other objects, >> it might require that. > > Nowadays it's stylistically better to write > > self.tasks = list(tasks) > > as it does just the same and makes it a little clearer what's going on > (though of course if tasks *isn't* a list it won't do *exactly* the same. > > regards > Steve No: self.tasks = list(tasks) is the same of self.tasks = tasks[:], not a replacement for self.tasks[:] = tasks , the latter performing a different operation, i.e. resetting the list self.tasks 'in place' without assigning it a different list. From marek.rocki at wp.pl Wed Feb 13 18:13:20 2008 From: marek.rocki at wp.pl (marek.rocki at wp.pl) Date: Wed, 13 Feb 2008 15:13:20 -0800 (PST) Subject: Floating point bug? References: Message-ID: <6eba298e-6888-462a-afa7-54fae02c3dce@y5g2000hsf.googlegroups.com> Not a bug. All languages implementing floating point numbers have the same issue. Some just decide to hide it from you. Please read http://docs.python.org/tut/node16.html and particularly http://docs.python.org/tut/node16.html#SECTION0016100000000000000000 Regards, Marek From jeff at schwabcenter.com Fri Feb 15 11:29:02 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Fri, 15 Feb 2008 08:29:02 -0800 Subject: copying files through Python In-Reply-To: <4e060b62-e537-44a6-8e98-8b8b1ab9a063@e6g2000prf.googlegroups.com> References: <15736d7f-fc9f-46a6-8d21-51ed77526944@h11g2000prf.googlegroups.com> <4e060b62-e537-44a6-8e98-8b8b1ab9a063@e6g2000prf.googlegroups.com> Message-ID: petercable at gmail.com wrote: > On Feb 13, 10:50 pm, Lalit wrote: > >> I need to write a program which would transfer files under one folder >> structure (there are sub folders) to single folder. > > > > find /fromdir -exec mv {} /todir \; -print > > -type f From cokofreedom at gmail.com Thu Feb 21 06:22:03 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Thu, 21 Feb 2008 03:22:03 -0800 (PST) Subject: newbie in python References: <1d24edf1-78f1-420e-9ca5-ef7e810e20cc@72g2000hsu.googlegroups.com> Message-ID: > >Can someone help me to get in the right track, and get a good move? > > http://wiki.python.org/moin/BeginnersGuide http://www.diveintopython.org/ From cwitts at gmail.com Wed Feb 13 12:05:37 2008 From: cwitts at gmail.com (Chris) Date: Wed, 13 Feb 2008 09:05:37 -0800 (PST) Subject: fromfunc functions References: <8542adb0-c59f-4c00-9605-61dd35145087@i29g2000prf.googlegroups.com> Message-ID: <94f896b2-c2f3-4a22-8231-7dfbba3eb4f7@e4g2000hsg.googlegroups.com> On Feb 13, 5:51 pm, azrael wrote: > I came across the fromfunc() function in numpy where you pass as an > argument the name of a function as a string and also the atributes for > the desired function. > > I find this extremly usefull and sexy. Can someone point me how write > a function of such capabilities class test_class(): def test_func(self, string): print string test = test_class() getattr(test, 'test_class'){'this is the test argument') getattr raises an Attribute Error though if the function doesn't exist so you'll need to catch that. From jeff at schwabcenter.com Wed Feb 13 13:35:59 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Wed, 13 Feb 2008 10:35:59 -0800 Subject: OT: Speed of light In-Reply-To: <87abm4g1tw.fsf@mulj.homelinux.net> References: <6f-dnfwZwvz6Ui3anZ2dnUVZ_oOnnZ2d@speakeasy.net> <13r2p6aivk1no9a@corp.supernews.com> <880dece00802121311n77f73515ve7db8a931825d958@mail.gmail.com> <87abm4g1tw.fsf@mulj.homelinux.net> Message-ID: <5LednYnShMTspS7anZ2dnUVZ_ternZ2d@comcast.com> Hrvoje Niksic wrote: > Jeff Schwab writes: > >> Jeroen Ruigrok van der Werven wrote: >>> -On [20080212 22:15], Dotan Cohen (dotancohen at gmail.com) wrote: >>>> Note that Google will give a calculator result for "1 kilogram in >>>> pounds", but not for "1 kilogram in inches". I wonder why not? After >>>> all, both are conversions of incompatible measurements, ie, they >>>> measure different things. >>> Eh? Last I checked both pound and kilogram are units of mass, so where is >>> the incompatibility? >> I've never heard of "pound" as a unit of mass. At least where I went >> to school (Boston, MA), "pound" is the English unit of force, "slug" >> is the (rarely used) English unit of mass, and "kilogram" is the SI >> unit of mass. > > It would be possible for US pound to only refer to weight, but I > cannot find references to corroborate it. For example, taken from > Wikipedia: > > In 1958 the United States and countries of the Commonwealth of > Nations agreed upon common definitions for the pound and the > yard. The international avoirdupois pound was defined as exactly > 453.59237 grams. > > The "pound-force" wikipedia entry documents "pound" being used as a > unit of force "in some contexts, such as structural engineering > applications." That's suprising (to me, anyway. We (Americans) all measure our weight in pounds. People talk about how much less they would weigh on the moon, in pounds, or even near the equator (where the Earth's radius is slightly higher). I remember converting pounds to Newtons, and vice versa, in school. Apparently, what everybody here calls a "pound," Wikipedia lists as a "pound-force." But I've only ever heard it called a pound, if anybody ever used "pound" as a unit of mass at school, they'd have been laughed at. http://en.wikipedia.org/wiki/Pound-force From hv at tbz-pariv.de Wed Feb 20 11:27:21 2008 From: hv at tbz-pariv.de (Thomas Guettler) Date: Wed, 20 Feb 2008 17:27:21 +0100 Subject: psycopg2: connect copy_from and copy_to In-Reply-To: <20fddf5a-b36c-4b0e-9171-3f0e7d24cedb@28g2000hsw.googlegroups.com> References: <6209kgF20tdpgU1@mid.individual.net> <20fddf5a-b36c-4b0e-9171-3f0e7d24cedb@28g2000hsw.googlegroups.com> Message-ID: <6232nbF208kt0U1@mid.individual.net> james.pye at gmail.com schrieb: > On Feb 19, 8:06 am, Thomas Guettler wrote: >> Any suggestions? > > If you don't mind trying out some beta quality software, you can try > my pg_proboscis driver. It has a DBAPI2 interface, but for you to use > COPY, you'll need to use the GreenTrunk interface: > Up to now I am happy with psycopg2. Why do you develop pg_proboscis? Thomas From steve at holdenweb.com Fri Feb 15 22:53:10 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 15 Feb 2008 22:53:10 -0500 Subject: Passing a callable object to Thread In-Reply-To: <7xzlu1bmdj.fsf@ruckus.brouhaha.com> References: <52465ed8-7d25-40ca-be69-478b308af879@u10g2000prn.googlegroups.com> <7xir0psq9l.fsf@ruckus.brouhaha.com> <452d63ea-3373-4393-9c28-38116f96d2e9@u10g2000prn.googlegroups.com> <7xzlu1bmdj.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Steve Holden writes: >> Assuming you're right, what alternative would you suggest? Would it >> allow parenthesized expressions to retain their customary meaning? > > It is kind of weird that there is even such a thing as a 1-tuple. I agree that zero-length and singleton tuples don't make a great deal of sense semantically. But by now there's been enough tuple-abuse that the general wish is to have tuples behave exactly like lists. Of course the singleton tuple was more or less bound to exist once the DB API started returning result rows as tuples, and I suspect that them empty tuple is an acceptable generalization. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From paul.nospam at rudin.co.uk Sat Feb 23 04:39:13 2008 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Sat, 23 Feb 2008 09:39:13 +0000 Subject: Return value of an assignment statement? References: <6d945394-739e-4c47-ad71-faaab8f9d566@34g2000hsz.googlegroups.com> <5sudnTSXrZY0aCDanZ2dnUVZ_rKtnZ2d@comcast.com> <5MSdncSVGdGriCPanZ2dnUVZ_vPinZ2d@comcast.com> <627eg8F21f45aU1@mid.uni-berlin.de> <13rtg6a341gqg5e@corp.supernews.com> Message-ID: <87ablsm2pq.fsf@rudin.co.uk> Steven D'Aprano writes: > On Fri, 22 Feb 2008 08:12:56 +0000, Marc 'BlackJack' Rintsch wrote: > >> A "variable" in >> programming languages is composed of a name, a memory location, possibly >> a type and a value. In C-like languages, where you put values in named >> and typed "boxes", the memory location and type are attached to the >> name. In Python both belong to the value. > > But Python objects don't have names, so by your own definition, they > aren't variables. Names are associated with namespaces, not objects. A > name must have one and only one object bound to it at any one time; > objects on the other hand can be bound to one name, or no name, or a > thousand names. The object itself has no way of knowing what names it is > bound to, if any. > > Or, to put it another way... Python doesn't have variables. Of course it all depends on how you choose to define "variable". Every programming language has slightly different semantics for variables. It would be perverse to describe something as a variable if it lacked any similarities with such in other programming languages, but I think it is misleading to say "python doesn't have variables". From Robert.Bossy at jouy.inra.fr Fri Feb 29 10:54:57 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Fri, 29 Feb 2008 16:54:57 +0100 Subject: joining strings question In-Reply-To: <6b41eaf1-05e1-4b04-8c31-6737166f267f@b1g2000hsg.googlegroups.com> References: <6b41eaf1-05e1-4b04-8c31-6737166f267f@b1g2000hsg.googlegroups.com> Message-ID: <47C82AD1.6090301@jouy.inra.fr> patrick.waldo at gmail.com wrote: > Hi all, > > I have some data with some categories, titles, subtitles, and a link > to their pdf and I need to join the title and the subtitle for every > file and divide them into their separate groups. > > So the data comes in like this: > > data = ['RULES', 'title','subtitle','pdf', > 'title1','subtitle1','pdf1','NOTICES','title2','subtitle2','pdf','title3','subtitle3','pdf'] > > What I'd like to see is this: > > [RULES', 'title subtitle','pdf', 'title1 subtitle1','pdf1'], > ['NOTICES','title2 subtitle2','pdf','title3 subtitle3','pdf'], etc... > > I've racked my brain for a while about this and I can't seem to figure > it out. Any ideas would be much appreciated. > As others already said, the data structure is quite unfit. Therefore I give you one of the ugliest piece of code I've produced in years: r = [] for i in xrange(0, len(data), 7): r.append([data[i], ' '.join((data[i+1], data[i+2],)), data[i+3], ' '.join((data[i+4], data[i+5],)), data[i+6]]) print r Cheers, RB From userprogoogle-139 at yahoo.co.uk Thu Feb 28 07:44:38 2008 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: Thu, 28 Feb 2008 04:44:38 -0800 (PST) Subject: URLlib2? Message-ID: <1c472e81-c4c6-4b24-b9fd-128f0c79f91c@z17g2000hsg.googlegroups.com> Hi, Probably a silly question but I am writing a CGI script which need to check the referring URL, can anyone provide any pointers? I have looked at URLLib2 and a couple of other libraries, but am slightly confused. Thanks in advance, rod From gagsl-py2 at yahoo.com.ar Mon Feb 11 13:15:00 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 11 Feb 2008 16:15:00 -0200 Subject: OT: Speed of light [was Re: Why not a Python compiler?] References: <28eead2f-a40c-414b-bd3d-a941f8a851a2@d70g2000hsb.googlegroups.com> <7da40f42-f64f-4939-a0dc-d24d1ff85f2d@v4g2000hsf.googlegroups.com> <13qjktdbe76da00@corp.supernews.com> <13qkhka8rln51c5@corp.supernews.com> <47adb0ca$0$31274$e4fe514c@dreader27.news.xs4all.nl> <13qs32es4eaj335@corp.supernews.com> <61aa39F1tt6irU1@mid.individual.net> <13r0si76tvs8o90@corp.supernews.com> Message-ID: En Mon, 11 Feb 2008 14:05:27 -0200, Grant Edwards escribi?: > On 2008-02-11, Steve Holden wrote: > >> Well the history of physics for at least two hundred years has >> been a migration away from the intuitive. > > Starting at least as far back as Newtonian mechanics. I once > read a very interesting article about some experiments that > showed that even simple newtonian physics is counter-intuitive. The inertia principle is counter-intuitive too, in a real world with friction. Things don't just "keep going" when impulse cease to exist; everyone knows that a running car eventually stops if the engine stops. That it "would" keep moving at the same speed in a straight line is an abstraction that people hardly can build from experience. -- Gabriel Genellina From kamonama2 at gmail.com Tue Feb 26 06:19:38 2008 From: kamonama2 at gmail.com (masayuki.takagi) Date: Tue, 26 Feb 2008 03:19:38 -0800 (PST) Subject: how to measure memory usage on Mac OSX ? References: <7d216514-8431-4f69-87c1-176ccaa765cb@i7g2000prf.googlegroups.com> <62038026-e757-46b4-a6eb-6508d0c75fe6@s19g2000prg.googlegroups.com> Message-ID: <368e3a21-15e3-4553-82be-6b107f506ea7@m23g2000hsc.googlegroups.com> On 2?26?, ??8:02, 7stud wrote: > On Feb 26, 3:43 am, "masayuki.takagi" wrote: > > > hi all, > > > i want to measure memory usage of my python process on Mac OSX. > > > i tired resource module, but it doesn't work on OSX. > > > how can i get it ? > > > thnx. > > > -- masayuki takagi > > #mac osx 10.4.7 > import resource > > print resource.getrusage(resource.RUSAGE_SELF) > > --output:-- > (0.009417, 0.020122999999999999, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, > 0, 0) hum... for example below, which elment of the output means the memory usage? the list i should use about 16MB. #mac osx 10.4.11 import resource i = range( 0, 1000000) print resource.getrusage(resource.RUSAGE_SELF) --output:-- (0.042582999999999996, 0.064561999999999994, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 103, 0) From obhatt at kentlaw.edu Mon Feb 25 18:52:18 2008 From: obhatt at kentlaw.edu (Bhatt, Omkar) Date: Mon, 25 Feb 2008 17:52:18 -0600 Subject: Python code for 2.5 and 2.4? In-Reply-To: <7xve4cr434.fsf@ruckus.brouhaha.com> Message-ID: <563040E07C98DB479C7718D36239EF0D0A1BD6B4@mail4.kentlaw.edu> PLEASE TAKE ME OFF THIS LIST! -----Original Message----- From: python-list-bounces+dhwani006=gmail.com at python.org [mailto:python-list-bounces+dhwani006=gmail.com at python.org] On Behalf Of Paul Rubin Sent: Monday, February 25, 2008 5:47 PM To: python-list at python.org Subject: Re: Python code for 2.5 and 2.4? Arnaud Delobelle writes: > Ok. In that case, the following is probably faster (in fact for long > iterables it may be equivalent to the builtin all): > > from itertools import ifilterfalse ... Nice. -- http://mail.python.org/mailman/listinfo/python-list From bharathv6 at gmail.com Wed Feb 27 07:17:17 2008 From: bharathv6 at gmail.com (bharath venkatesh) Date: Wed, 27 Feb 2008 17:47:17 +0530 Subject: refreshing the cache time of a key Message-ID: <910313af0802270417s758f7962h656310da1b11e62@mail.gmail.com> hi .. is it possible to refresh the cache time of a key with out having to retrieving the cached data and storing it back in memcache .. for example if a data is cached for 1 hour and at the 50th minute from the time this data has been cached i want to store it in the cache for 1 more hour ..is there a function to refresh the cache time by knowing the key of data with out having to do get and set i.e data=mc.get(key) mc.set(key,data,3600) # 1 more hour -------------- next part -------------- An HTML attachment was scrubbed... URL: From sgeiger at ncee.net Wed Feb 20 10:21:41 2008 From: sgeiger at ncee.net (Shane Geiger) Date: Wed, 20 Feb 2008 09:21:41 -0600 Subject: smtplib & gnupg In-Reply-To: References: Message-ID: <47BC4585.3030209@ncee.net> To the best of my knowledge, GNUPG acts upon the body of the message. If you think about it you should realize that the header of the message cannot be encrypted, as it will be handled by mail servers that have no knowledge of GNUPG or your encryption keys. I am further emboldened to make this assertion because the encryption takes place before the message is sent--that is, before the headers are completely formed. Brot wrote: > Hello, > > at the moment my program sends mail with smtplib. Is there a chance to > sign and/or encode/cipher this mails with GnuPG? > If yes, does anyone have some sample code? > > Regards > Bernd > -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy From lists at cheimes.de Tue Feb 19 10:56:24 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 19 Feb 2008 16:56:24 +0100 Subject: Seemingly odd 'is' comparison. In-Reply-To: <13rk2ho7b8h1c85@corp.supernews.com> References: <47b36135$0$26076$88260bb3@free.teranews.com> <13rk2ho7b8h1c85@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > "is" is a comparison operator: it compares identity, not equality. It is > more or less equivalent to the expression id(x) == id(y). Yes, the implementation of the is operator comes down to the comparison of PyObject* pointer addresses and in CPython id() returns the address of the PyObject*. But it's very important to understand that "a is b" can have a different result than "id(a) == id(b)". CPython uses all sorts of tricks to speed up common operations. Memory allocation/de-allocation and object creation can have a huge speed impact. Therefor Python uses free lists to keep some empty objects around for recycling. Small integers are cached, too. Compare >>> id(0) 135689168 >>> id(1) 135689184 >>> id(2) 135689200 with >>> id(2000) 3084440752 >>> id(2001) 3084440752 >>> id(2002) 3084440752 to see the effect of small int cache vs. int free list. Christian From gagsl-py2 at yahoo.com.ar Tue Feb 19 06:06:12 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 19 Feb 2008 03:06:12 -0800 (PST) Subject: How to get current module object References: <47B87C28.3030302@gmail.com> <47B9B6FE.50508@gmail.com> Message-ID: On 19 feb, 03:33, Alex wrote: > GabrielGenellinawrote: > > En Mon, 18 Feb 2008 14:49:02 -0200, Alex escribi?: > >> That's what I've been searching for, thanks. By the way, I know it might > >> be trivial question... but function and class namespaces have __name__ > >> attribute too. Why is global one always returned? > > I don't understand the question (even with the later correction ? > > namespaces->objects) > > There's no question anymore, I just failed to distinguish function local > variables (which don't include __name__) and function object's attributes>>> Why do you want to get the module object? globals() returns the module > >>> namespace, its __dict__, perhaps its only useful attribute... > > >> To pass it as a parameter to a function (in another module), so it can > >> work with several modules ("plugins" for main program) in a similar ? > >> manner. > > > The function could receive a namespace to work with (a dictionary). Then ? > > you just call it with globals() == the namespace of the calling module. > > Yes, but access to module seems more verbose: > > ?>>> module_dict['x']() > xxx > > Instead of just: > > ?>>> module.x() > xxx You could write a wrapper class on the client side, but I guess it's easier to pass the module object directly, as you said earlier. Anyway, this class would fake attribute access for dictionary entries: py> class Idx2Attr(object): ... def __init__(self, d): self.__dict__[None] = d ... def __getattr__(self, name): ... try: return self.__dict__[None][name] ... except KeyError: raise NameError, name ... def __setattr__(self, name, value): ... self.__dict__[None][name]=value ... py> import htmllib py> dir(htmllib) ['AS_IS', 'HTMLParseError', 'HTMLParser', '__all__', '__buil tins__', '__doc__', '__file__', '__name__', 'sgmllib', 'test '] py> mod = Idx2Attr(htmllib.__dict__) # htmllib.__dict__ is what you get if you use globals() inside htmllib py> mod.__file__ 'C:\\APPS\\PYTHON25\\lib\\htmllib.pyc' py> mod.foo = 3 py> htmllib.foo 3 ([None] is to avoid name collisions to some extent) -- Gabriel Genellina From brunorenostro at gmail.com Tue Feb 12 10:25:14 2008 From: brunorenostro at gmail.com (btox) Date: Tue, 12 Feb 2008 07:25:14 -0800 (PST) Subject: Free Certifications from www.Brainbeez.com References: <40113f07-d18f-4b44-a2f7-25e3c4ff3e52@s13g2000prd.googlegroups.com> Message-ID: <420350fa-89f8-4f42-a4cb-166e1b926d52@s8g2000prg.googlegroups.com> Ria escreveu: > Hi, > > www.brainbeez.com is offering free certifications on various IT > and NON-IT subjects like Aptitude, English, C, C++, JAVA, ORACLE, > FINANCE, MARKETING ETC., > > Do visit www.brainbeez.com and get certified for free instantly. > Certificate is directly send to your email account once you qualify > the exam. > > Thanks, > > Ria ! Good! From gabriel.rossetti at mydeskfriend.com Mon Feb 25 05:36:14 2008 From: gabriel.rossetti at mydeskfriend.com (Gabriel Rossetti) Date: Mon, 25 Feb 2008 11:36:14 +0100 Subject: Parent instance attribute access Message-ID: <47C29A1E.2030306@mydeskfriend.com> Hello, I have something weird going on, I have the following (simplified) : class MyFactory(..., ...): def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs ... class MyXmlFactory(MyFactory): def __init__(self, *args, **kwargs): MyFactory.__init__(self, *args, **kwargs) #self.args = args #self.kwargs = kwargs ... def build(self, addr): p = self.toto(*self.args, **self.kwargs) when build is called I get this : exceptions.AttributeError: MyXmlFactory instance has no attribute 'args' If I uncomment "self.args = args" and "self.kwargs = kwargs" in __init__(...) it works. I find this strange, since in OO MyXmlFactory is a MyFactory and thus has "self.args" and "self.kargs", and I explicitly called the paret __init__(...) method, so I tried this small example : >>> class A(object): ... def __init__(self, *args, **kargs): ... self.args = args ... self.kargs = kargs ... self.toto = 3 ... >>> class B(A): ... def __init__(self, *args, **kargs): ... A.__init__(self, *args, **kargs) ... def getToto(self): ... print str(self.toto) ... >>> b = B() >>> b.getToto() 3 so what I though is correct, so why does it not work with args and kargs? BTW, If I build a MyFactory and call build, it works as expected. Thanks, Gabriel -- www.mydeskfriend.com PSE - C (EPFL) 1015 Ecublens, Switzerland Tel: +41 21 601 52 76 Mob: +41 76 442 71 62 From iceboy127 at yahoo.com Mon Feb 18 21:57:43 2008 From: iceboy127 at yahoo.com (katie smith) Date: Mon, 18 Feb 2008 18:57:43 -0800 (PST) Subject: ROUNDING??? Message-ID: <381743.3150.qm@web57311.mail.re1.yahoo.com> in python im doing the problem 255/494 it keeps giving me 0 instead of .51.... what am i doing wrong? please help me I have been looking for hours ____________________________________________________________________________________ Never miss a thing. Make Yahoo your home page. http://www.yahoo.com/r/hs From castironpi at gmail.com Tue Feb 12 13:05:59 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 12 Feb 2008 10:05:59 -0800 (PST) Subject: dream hardware Message-ID: What is dream hardware for the Python interpreter? From darcy at druid.net Tue Feb 26 10:08:24 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 26 Feb 2008 10:08:24 -0500 Subject: How about adding rational fraction to Python? In-Reply-To: References: <649ac8a9-ae09-4e9b-85c2-f37043af21fd@28g2000hsw.googlegroups.com> <0d1955fc-762c-44e1-a5d8-372c71458455@p25g2000hsf.googlegroups.com> <36204e6f-0d82-449b-8ca5-c819ace9a55a@p73g2000hsd.googlegroups.com> <9503b14b-7bd5-42b4-b3f7-673d0ebd7feb@c33g2000hsd.googlegroups.com> <602ac27c-4aaa-49b2-bee2-1e0e0c705983@i7g2000prf.googlegroups.com> <1204034122.3318.3.camel@aalcdl07.lib.unc.edu> Message-ID: <20080226100824.fdc81ac7.darcy@druid.net> On Tue, 26 Feb 2008 06:45:45 -0800 (PST) Carl Banks wrote: > On Feb 26, 9:29 am, "D'Arcy J.M. Cain" wrote: > > If 3/4 ever returned 0.75 in any language I would drop that language. > > Have fun dropping Python, then, chief. Integer division with / is > already deprecated, can be disabled ever since Python 2.4, and will be > wholly removed in Python 3.0. I have not been following Python development that closely lately so I was not aware of that. I guess I won't be going to Python 3 then. It's great that Python wants to attract young, new programmers. Too bad about us old farts I guess. How soon before 2.x is completely deprecated and I have to become a Walmart greeter? -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From castironpi at gmail.com Sun Feb 17 17:27:05 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 17 Feb 2008 14:27:05 -0800 (PST) Subject: Solve a Debate References: <82ol85-0o5.ln1@darkstargames.dnsalias.net> Message-ID: > days_in_month 12: > 31 > 30 > 28 > 31 > ... > 30 > 31 > assign $days days_in_month[$month] This is missing days_in_month 12: 31 break 30 break Or the addition add $x' $x offset store $r0 $x' assign $days $r0 Is that 4 ticks or 5; or 24 blips? From apt.shansen at gmail.com Fri Feb 29 23:22:05 2008 From: apt.shansen at gmail.com (Stephen Hansen) Date: Fri, 29 Feb 2008 20:22:05 -0800 Subject: Is crawling the stack "bad"? Why? In-Reply-To: <7fc19187-2684-4831-90c4-2e4e44ee057d@i12g2000prf.googlegroups.com> References: <7xfxvhfuro.fsf@ruckus.brouhaha.com> <0ba4f68c-4046-4664-b2bb-2e8f418a5d42@41g2000hsc.googlegroups.com> <7xmyppzdoi.fsf@ruckus.brouhaha.com> <12f33c86-e1b4-45ec-8a87-d5ba7c67501d@t66g2000hsf.googlegroups.com> <7fc19187-2684-4831-90c4-2e4e44ee057d@i12g2000prf.googlegroups.com> Message-ID: <7a9c25c20802292022n106f9bb5jeccff0f3eb6e37c@mail.gmail.com> > > > Seriously, crawling the stack introduces the potential for disaster in > > your program, since there is no guarantee that the calling code will > > provide the same environment i future released. So at best you tie your > > solution to a particular version of a particular implementation of > Python. > > I'm gathering that the general argument is entirely centered around > portability and future-proofing of code. This certainly makes sense. > I could try and argue that that doesn't matter for write-once-change- > never code, but anything I'd say there might as well be applied to an > argument saying that writing crappy code is actually ok. And then I > would need to be committed for thinking that write-once-change-never > code actually exists. I'm making myself sick as I type this. There's a difference between "perfect future-proofing" and writing code that will at least minimize the amount of maintenance with Python upgrades. Consider: if you walk the stack to get this data instead of using thread local storage, there is zero guarantee that your code will work from one point release to another. It might work in 2.5.1; but a small and inconsequential bug could make them alter the private internals of a class you're walking into so that a variable name is different inside. They might not /need/ to-- but what if the maintainer did a minor style update at the same time? As long as the API is the same, the behavior the same,... it'd get through, and it likely wouldn't even be documented in the release notes for you to catch. If you rely on private internals-- and local variables up your calling stack oh so count-- then you're just inviting breakage. The published API's aren't likely to change except extremely rarely, and when they do they're apt to have a very clear notice provided, and there's usually a very straight-forward way to support both. Crawling the stack into code you don't control ties you directly to one specific implementation, in one specific version-- if it works later, its pure chance you can't rely on, and it could break at any point. Relying on API's have unit tests, deprecation warnings, documentation, and behavior reversions being classified all as bugs, all providing you with confidence that something you code might still work in the next point release... and likely the next major release, too. --Stephen -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeff at schwabcenter.com Mon Feb 18 17:28:55 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Mon, 18 Feb 2008 14:28:55 -0800 Subject: Python Memory Manager In-Reply-To: <7885d6a5-0aa0-4ef5-b409-a954170ae9da@i7g2000prf.googlegroups.com> References: <0c69faf6-c019-425b-b988-fc2b76befd3d@60g2000hsy.googlegroups.com> <7xejbb6zss.fsf@ruckus.brouhaha.com> <7885d6a5-0aa0-4ef5-b409-a954170ae9da@i7g2000prf.googlegroups.com> Message-ID: MartinRinehart at gmail.com wrote: > > Paul Rubin wrote: >> The problem here is with a high allocation rate, you have to GC a lot >> more often, which typically involves copying live data. > > This is last century's issue. Copying data, RAM to RAM, is nearly free > using the Intel architecture. What's "the Intel architecture?" Do you mean the x86_64 architecture that was actually developed by AMD, or x86 for x > some number, or do you actually mean IA64? > > This short article, http://www.martinrinehart.com/articles/repz.html > explains why. > > I'd use one int per clock as a rule of thumb for the current copy rate > in a single-core CPU. From vsevolod.balashov at gmail.com Tue Feb 26 06:03:03 2008 From: vsevolod.balashov at gmail.com (Vsevolod Balashov) Date: Tue, 26 Feb 2008 03:03:03 -0800 (PST) Subject: Question about PyPI and 'easy_install' References: <700d4ba3-e088-4c7d-a4d8-96b68dccb61e@71g2000hse.googlegroups.com> Message-ID: On Feb 24, 10:38 pm, makoto kuwata wrote: > Hi, > > I have a trouble around PyPI and easy_install. > > I have developed OSS (Tenjin) and registered it to PyPI.http://pypi.python.org/pypi/Tenjin/0.6.1 > > But I can't install it by 'easy_install' command. > Hi! I`m think this patch is helpful for you ---BEGIN PATCH--- --- setup.py.orig 2007-10-23 03:54:18.000000000 +0400 +++ setup.py 2008-02-26 14:08:44.660000000 +0300 @@ -6,12 +6,10 @@ import sys, re -if len(sys.argv) > 1 and sys.argv[1] == 'egg_info': - from ez_setup import use_setuptools - use_setuptools() -from distutils.core import setup +from ez_setup import use_setuptools +from setuptools import setup -name = 'pyTenjin' +name = 'Tenjin' version = '0.6.1' author = 'makoto kuwata' email = 'kwa at kuwata-lab.com' ---END PATCH--- PS Thank you for excellent job. -- Vsevolod Balashov http://vsevolod.balashov.name From lists at cheimes.de Sun Feb 10 15:24:43 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 10 Feb 2008 21:24:43 +0100 Subject: python 3.0 memory leaking? In-Reply-To: <20080210200454.GE28991@nexus.in-nomine.org> References: <20080210200454.GE28991@nexus.in-nomine.org> Message-ID: Jeroen Ruigrok van der Werven wrote: > For me, a relative newbie to Python, the entire memory allocation issue is > not transparent at all and information about it is scattered across the net. > One of the things I hope to contribute to in the coming year is to make sure > the entire area of Python memory use and proper coding is better understood. Python uses its own memory allocator for small objecst (< 257 bytes). Larger objects are allocated directly with malloc, smaller objects end up in arenas. The code is well documented in http://svn.python.org/view/python/trunk/Objects/obmalloc.c?rev=56476&view=auto Several objects keep a free list for performance reasons. Free list save some extra mallocs and initialization of data structures. I've renamed all free lists in Python 2.6 to "free_list". Ints and floats are using their own block allocation algorithm. The code predates Python's pymalloc code. I'm working on replacing the code with pymalloc because pymalloc-ed memory is given back to the OS. The int and float free lists keep their sizes until the Python process ends. Christian From grante at visi.com Tue Feb 26 16:33:10 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 26 Feb 2008 21:33:10 -0000 Subject: How about adding rational fraction to Python? References: <0d1955fc-762c-44e1-a5d8-372c71458455@p25g2000hsf.googlegroups.com> <36204e6f-0d82-449b-8ca5-c819ace9a55a@p73g2000hsd.googlegroups.com> <9503b14b-7bd5-42b4-b3f7-673d0ebd7feb@c33g2000hsd.googlegroups.com> <602ac27c-4aaa-49b2-bee2-1e0e0c705983@i7g2000prf.googlegroups.com> <1204034122.3318.3.camel@aalcdl07.lib.unc.edu> <20080226100824.fdc81ac7.darcy@druid.net> <1204051178.4191.11.camel@aalcdl07.lib.unc.edu> <20080226135152.6991f09b.darcy@druid.net> <1204053380.5087.7.camel@aalcdl07.lib.unc.edu> <7xejaz4exv.fsf@ruckus.brouhaha.com> <7xk5kra0p1.fsf@ruckus.brouhaha.com> Message-ID: <13s91cmlkfpf611@corp.supernews.com> On 2008-02-26, Paul Rubin wrote: > "D'Arcy J.M. Cain" writes: >> > http://en.wikipedia.org/wiki/Natural_number >> Recheck the context. I was talking about the natural result, not >> natural numbers. > > The natural result of doing arithmetic with natural numbers is more > natural numbers. OK, but I thought we were talking about computer integers. -- Grant Edwards grante Yow! My mind is a potato at field ... visi.com From nicola.musatti at gmail.com Tue Feb 26 08:23:11 2008 From: nicola.musatti at gmail.com (Nicola Musatti) Date: Tue, 26 Feb 2008 05:23:11 -0800 (PST) Subject: Article of interest: Python pros/cons for the enterprise References: <2f1527a7-2f66-44c7-9665-4d8ff01fa5ab@28g2000hsw.googlegroups.com><47bd4a24$0$25225$426a74cc@news.free.fr> <036e93e6-5840-4a3c-8642-67a0a9ec44f2@i7g2000prf.googlegroups.com> <5ae1e7e8-48bc-4919-bd33-72b910c633ee@41g2000hsc.googlegroups.com> Message-ID: <24e34792-7a10-4179-af6d-cc6554fe9d2a@34g2000hsz.googlegroups.com> On Feb 25, 3:59 pm, Sebastian Kaliszewski wrote: [...] > 1. Your "generic" resource-management infrastructure is not generic to begin > with! It does not work for mutually dependant resources. How so? Could you give a concrete example? > 2. Your "generic" infrastructure increases burden on the programmer > everywhere any resorce (including trivial one like memory) is used, while > GC kills that burden in 95% of the cases. C++ish approach puts the notion > of ownership everywhere - both in 95% of cases where it's useless and in > remaining 5% where it's actually needed. That's not reduced effort by any > means. Like others around here you seem not to be aware of the existence of the standard C++ library. That and local variables usually deal with well over half the cases of memory management in any non trivial application, and boost::shared_ptr can deal with a good portion of the rest. > 3. You can't handle clean-up errors in reasonable way in C++ish approach, so > anything more complex should not by handled that way anyway. So it's okay for a Python mechanism to deal with 95% of the cases, but not for a C++ one? At least in C++ resource management only becomes more complicated if you need more control. Cheers, Nicola Musatti From paddy3118 at googlemail.com Sun Feb 10 12:31:02 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sun, 10 Feb 2008 09:31:02 -0800 (PST) Subject: Better way to negate a boolean list? References: <5e23677e-ced7-493f-84e4-aa42b65e8437@l32g2000hse.googlegroups.com> Message-ID: <1e1d0db9-5e4c-4197-b9b1-d0bcaf8b14c4@c4g2000hsg.googlegroups.com> On Feb 10, 1:41 pm, Steve Holden wrote: > Paddy wrote: > > On Feb 10, 7:46 am, David Tr?mouilles wrote: > >> Hi, > > >> Is there any better (shorter) way to negate a boolean list than: > >> >>> negated_boolean_list = [not elem for elem in boolean_list] > >> ? > > >> I tried: > >> >>> map(not, boolean_list) > >> but it seems that "not" is not a function. > > >> Thanks in advance, > > >> David > > > Try [not x for x in boolean_list] > > This six-character shortening by renaming the comprehension's bound > variable was a joke, right? No, Of course not! It's much worse - I completely missed the line beginning negated_.... on first and second reading. I am indeed getting older, although I had thought I was way off my dotage. - Paddy. From hniksic at xemacs.org Thu Feb 7 18:25:46 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 08 Feb 2008 00:25:46 +0100 Subject: Why not a Python compiler? References: <28eead2f-a40c-414b-bd3d-a941f8a851a2@d70g2000hsb.googlegroups.com> <81339c25-f9b6-47a1-941e-8ae39c35773c@e6g2000prf.googlegroups.com> <98a1bc2d-290b-4b6d-8a3d-eda7666d2b8b@l1g2000hsa.googlegroups.com> <13qmtu5j1b1p6a2@corp.supernews.com> Message-ID: <8763x0fix1.fsf@mulj.homelinux.net> Steven D'Aprano writes: > Be fair -- he's asking what specific features of Python make it > hard. That's a reasonable question. Indeed. The best explanation I've seen explained goes something like this: imagine a hypothetical Python compiler that achieves native compilation by compiling to Common Lisp and using the CL's compiler to produce native code. Upon encountering the expression such as: a + b the compiler could do little else except translate it to something like: (python:add a b) In order to correctly implement Python addition, python:add needs to do a lot of work at run-time. It needs to check for __add__ method of one or both operands without assuming what it does, since a user-defined class is free to define __add__ to do whatever it pleases. The compiler could attempt to infer the types of operands, but that is hard since an expression such as "a = module.SomeClass()" completely changes meaning if module.SomeClass or module.SomeClass.__add__ change. Such changes may seem improbable, but fact is that being able to do them is a documented part of the language, and a lot of code makes good use of it. Assuming these things don't happen means the compiler doesn't implement Python. This applies not only to addition; expressions such as "foo.bar", which include any method call, would be translated to (python:getattr foo "bar"), and so on. Most functions would have to construct actual tuples, since a function can be replaced with one that takes *args. Again, optimizing almost any of this away would change the semantics of Python. From the ability to assign to classes, to modules, to globals(), and to __dict__'s, literally anything can change at run-time. *Some* kinds of runtime dispatches can be sped up by setting up sophisticated caches (one such cache for methods is being applied to CPython), but getting that right without breaking correctness is quite tricky. Besides the same caches could be used to speed up CPython too, so they don't constitute an advantage of the compiler. The main determinant of Python's performance isn't the interpreter overhead, but the amount of work that must be done at run-time and cannot be moved to compile-time or optimized away. From jeff at schwabcenter.com Tue Feb 26 17:10:45 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Tue, 26 Feb 2008 14:10:45 -0800 Subject: How about adding rational fraction to Python? In-Reply-To: <7xk5kra0p1.fsf@ruckus.brouhaha.com> References: <0d1955fc-762c-44e1-a5d8-372c71458455@p25g2000hsf.googlegroups.com> <36204e6f-0d82-449b-8ca5-c819ace9a55a@p73g2000hsd.googlegroups.com> <9503b14b-7bd5-42b4-b3f7-673d0ebd7feb@c33g2000hsd.googlegroups.com> <602ac27c-4aaa-49b2-bee2-1e0e0c705983@i7g2000prf.googlegroups.com> <1204034122.3318.3.camel@aalcdl07.lib.unc.edu> <20080226100824.fdc81ac7.darcy@druid.net> <1204051178.4191.11.camel@aalcdl07.lib.unc.edu> <20080226135152.6991f09b.darcy@druid.net> <1204053380.5087.7.camel@aalcdl07.lib.unc.edu> <7xejaz4exv.fsf@ruckus.brouhaha.com> <7xk5kra0p1.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "D'Arcy J.M. Cain" writes: >>> http://en.wikipedia.org/wiki/Natural_number >> Recheck the context. I was talking about the natural result, not >> natural numbers. > > The natural result of doing arithmetic with natural numbers is more > natural numbers. Back when I was just a wee little developer, I was taught that division over the natural number was *not* a closed operation. (I still like integer division, and I'm OK with the fact that it truncates.) From tjreedy at udel.edu Thu Feb 21 18:13:24 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 21 Feb 2008 18:13:24 -0500 Subject: Return value of an assignment statement? References: <6d945394-739e-4c47-ad71-faaab8f9d566@34g2000hsz.googlegroups.com><835a4fc1-f62a-4141-bca4-4e4f52519466@s37g2000prg.googlegroups.com> <5sudnTSXrZY0aCDanZ2dnUVZ_rKtnZ2d@comcast.com> Message-ID: "Jeff Schwab" wrote in message news:5sudnTSXrZY0aCDanZ2dnUVZ_rKtnZ2d at comcast.com... | That's the same behavior I would expect in C, on the grounds that C | What I found confusing at first was | that the same variable will either directly store or merely refer to an | object, depending on the type of the object: Since names and collection slots always refer to objects, I find the above confusing. Can you clarify what difference you percieve? tjr From arkanes at gmail.com Mon Feb 4 12:45:43 2008 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 4 Feb 2008 11:45:43 -0600 Subject: Python GUI toolkit In-Reply-To: <47A74182.7020306@codebykevin.com> References: <42c7d139-3520-4d73-85cd-f67e3bdacd5a@c4g2000hsg.googlegroups.com> <47A735D0.9000902@codebykevin.com> <47A74182.7020306@codebykevin.com> Message-ID: <4866bea60802040945t4db4120di50dc2471ac38a7c2@mail.gmail.com> On Feb 4, 2008 10:46 AM, Kevin Walzer wrote: > Chris Mellon wrote: > > > > > I didn't say inherently unable, I said the toolkit doesn't provide it. > > Note that you said that you did a lot of work to follow OS X > > conventions and implement behavior. The toolkit doesn't help you with > > any of this. A mac-native toolkit (or one that strives for native > > behavior, like wxPython) eliminates a lot of this work (although, of > > course, not all). > > > If the toolkit doesn't provide it, then I think that means "inherently > unable." > Of course it doesn't, because you can implement it yourself. Which is what you do. Tile itself is inherently unable to provide this because it's a theming mechanism. > On the Mac, Tk provides a mechanism that allows hooking up arbitrary > events to arbitrary keyboard. Something like: > > self.bind('', lambda event: > self.authorizeCommand(self.installPackage)) > > I have to specify the key-combination--that's all. One line of code. No > implementing of keyboard bindings in C or at the Tcl/Tk or even > Python-Tkinter level--it's all already defined by the toolkit. > I know how toolkits work. > By contrast, Cocoa/Objective-C has a rather complex system for defining > keyboard events: > > http://developer.apple.com/documentation/Cocoa/Conceptual/EventOverview/HandlingKeyEvents/chapter_6_section_1.html#//apple_ref/doc/uid/10000060i-CH7-SW1 > > PyObjC is a thin wrapper over Objective-C, so you'd have to do the > equivalent calls in Python to implement custom keyboard behavior. > > It is true that Cocoa some convenience methods in Interface Builder, > i.e. common menu commands don't require any extra code: if you are > developing a document-based application, "Command-C" is implemented in > the menu and in the frameworks as "copy (text, image, whatever) to > clipboard." But "Command-C" also works identically in the Tk console. > > Tk does lack some things. It doesn't support drag-and-drop on the Mac. > It doesn't hook into some of the newer Mac visual styles. Getting access > to this would require an extension or patching Tk's core. In those > events, I emulate the behavior or appeareance, which Tk makes very easy. > I'm not sure how you keep referring to things you implement yourself as something that the toolkit supports. As a brief example, some features that wxPython provides to aid in native "feel" and not just look: Stock button support allows you to have native button location, order and labelling. Sizer support allows for differently sized controls to be positioned with the same layout. Stock menu IDs (like preferences and "About this application...") will be labelled and placed correctly. Accelerators will automatically map between Command and Control. Standard path support to find appropriate user directories. All of these are things that you can do yourself, of course. You could have implemented Tile yourself, too, to get the (mostly) native look. The point is what the toolkit provides, and Tk+Tile, while it mostly provides native look, does *not* provide native feel. If you want native feel, you need to implement it yourself. From jeff at jmcneil.net Thu Feb 21 14:43:17 2008 From: jeff at jmcneil.net (Jeff McNeil) Date: Thu, 21 Feb 2008 14:43:17 -0500 Subject: Choosing a Metaclass? In-Reply-To: <82d28c40802211011h66cce3e8t31f6534e3732314@mail.gmail.com> References: <82d28c40802211011h66cce3e8t31f6534e3732314@mail.gmail.com> Message-ID: <82d28c40802211143w29e903a9mf06adcbb2e24f733@mail.gmail.com> Never mind, I've figured it out. The build_class function looks at the '__class__' attribute of the first base class if there's no explicit __metaclass__ attribute. By calling type directly, the __class__ attribute as returned by MyMeta is, in fact, type. Should have just looked at the source to begin with. On 2/21/08, Jeff McNeil wrote: > > Hi list, > > Hopefully a quick metaclass question. In the following example, MyMeta is > a metaclass that does not inherit directly from type: > > #!/usr/bin/python > > class MyMeta(object): > def __new__(cls, name, bases, vars): > print "MyMeta.__new__ called for %s" % name > return type(name, bases, vars) > > class MetaWrapper(object): > __metaclass__ = MyMeta > > class M(MetaWrapper): > pass > > [jeff at marvin ~]$ python t.py > MyMeta.__new__ called for MetaWrapper > [jeff at marvin ~]$ > > When I run that script, it's apparent that although M inherits from > MetaWrapper, it does not use MyMeta as it's metaclass. However, if I change > MyMeta to be a subclass of builtin type, it works as I would expect: > > [jeff at marvin ~]$ cat t.py > #!/usr/bin/python > > class MyMeta(type): > def __new__(cls, name, bases, vars): > print "MyMeta.__new__ called for %s" % name > return super(MyMeta, cls).__new__(cls, name, bases, vars) > > class MetaWrapper(object): > __metaclass__ = MyMeta > > class M(MetaWrapper): > pass > > [jeff at marvin ~]$ python t.py > MyMeta.__new__ called for MetaWrapper > MyMeta.__new__ called for M > [jeff at marvin ~]$ > > How exactly does Python choose which MC it will use when building a > class? It doesn't seem to me that the parent class of MyMeta should matter > in this case? > > Thanks! > > Jeff > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From frithiof.jensen at diespammerdie.jensen.tdcadsl.dk Fri Feb 22 08:40:49 2008 From: frithiof.jensen at diespammerdie.jensen.tdcadsl.dk (Frithiof Andreas Jensen) Date: Fri, 22 Feb 2008 14:40:49 +0100 Subject: Linux/Python Issues References: <47bad186$0$31953$426a74cc@news.free.fr> Message-ID: <47bed0ba$0$2104$edfadb0f@dtext02.news.tele.dk> "Bruno Desthuilliers" skrev i en meddelelse news:47bad186$0$31953$426a74cc at news.free.fr... > MartinRinehart at gmail.com a ?crit : > So, here's the basic scheme: > > - download the source tarball, preferably in /usr/local/src > - unpack it > - cd into the unpacked source directory > - *carefully* read the README, INSTALL and other relevant docs > - run ./configure with the relevant options > - run make > - run make install > > Wasn't too hard, was it ?-) It's a wee bit harder: Since he's got a package based distribution, the O.P. would do well to learn how to build source packages for that distribution otherwise he will eventually end up with a mess. The learning curve for packages is steep. For a Debian-based system the easiest way to roll custom packages is I.M.O. to use "pbuilder" so the system does not get totally polluted by build dependencies and other only-ever-used-once cruft. Pbuilder works on Ubuntu too - I have an old SUN Ultra SPARC 10 so very occasionally I need to package/rebuild src-packages some tool that is not in the distribution. > And before you say it: yes indeed, it assumes you know how to use the > command line, navigate your filesystem, copy/move things around, unpack an > archive, read a text file etc... IOW, some more 'common *n*x knowledge' > that you just can't hope to avoid learning if you want to properly use a > *n*x system. Sorry. Same story on Windows, really. People just forget how hard that was to learn. From cfbolz at gmx.de Tue Feb 26 18:25:07 2008 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Wed, 27 Feb 2008 00:25:07 +0100 Subject: Is crawling the stack "bad"? Why? In-Reply-To: <7xmyppzdoi.fsf@ruckus.brouhaha.com> References: <7xfxvhfuro.fsf@ruckus.brouhaha.com> <0ba4f68c-4046-4664-b2bb-2e8f418a5d42@41g2000hsc.googlegroups.com> <7xmyppzdoi.fsf@ruckus.brouhaha.com> Message-ID: <47C49FD3.3@gmx.de> Paul Rubin wrote: > Russell Warren writes: >> That is exactly where I started (creating my own request handler, >> snagging the IP address and stashing it), but I couldn't come up with >> a stash location that would work for a threaded server. > > How about a dictionary indexed by by the thread name. It's pretty > lame, though, that the rpc server module itself doesn't make the > request available to the rpc responder. Maybe you should submit a > patch. > >> My biggest specific fear at the moment is that sys._frame will do >> funky things with multiple threads, > > You should not rely on anything that implementation specific at all. > What happens if you want to switch to pypy? Apart from the fact that the idea of walking the stack to get info is indeed rather crazy, PyPy supports sys._getframe and friends perfectly fine (I think even Jython does, but I am not quite sure). In general PyPy tries to implement all these "internals" of CPython as closely as it is sane to do so. Stuff like inspecting code, function, frame, method objects is very closely mirrored but of course small differences exist: cfbolz at gauss:~$ python Python 2.5.1 (r251:54863, Oct 5 2007, 13:36:32) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> dir(dir) ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__str__'] cfbolz at gauss:~$ pypy-c-46371-faassen Python 2.4.1 (pypy 1.0.0 build 46371) on linux2 Type "help", "copyright", "credits" or "license" for more information. >>>> dir(dir) ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__setstate__', '__str__', '__weakref__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name'] >>>> dir.func_code >>>> dir.func_name 'dir' Cheers, Carl Friedrich Bolz From gregory.bronner at lehman.com Fri Feb 29 14:08:49 2008 From: gregory.bronner at lehman.com (Bronner, Gregory) Date: Fri, 29 Feb 2008 14:08:49 -0500 Subject: How to subclass ints to prevent comparisons? In-Reply-To: References: Message-ID: <21CFA1FC32D3214EBFA2F449FF211E310EAD2947@nypcmg1exms318.leh.lbcorp.lehman.com> I'm trying to create a type-safe subclass of int (SpecialInt) such that instances of the class can only be compared with ints, longs, and other subclasses of SpecialInt -- I do not want them to be compared with floats, bools, or strings, which the native int implementation supports. Obviously, I could overload __lt_, __eq__, __le__, etc, and write a bunch of boilerplate code. Should this code throw an exception if the types are not comparable? What would I lose by doing that? The native implementation of int goes to great lengths to allow illogical comparisons such as the one below. >>> import xml as x >>> x >>> >>> x>4 True >>> x<4 False - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. -------- IRS Circular 230 Disclosure: Please be advised that any discussion of U.S. tax matters contained within this communication (including any attachments) is not intended or written to be used and cannot be used for the purpose of (i) avoiding U.S. tax related penalties or (ii) promoting, marketing or recommending to another party any transaction or matter addressed herein. From roger.dahlstrom at gmail.com Mon Feb 4 12:53:11 2008 From: roger.dahlstrom at gmail.com (rdahlstrom) Date: Mon, 4 Feb 2008 09:53:11 -0800 (PST) Subject: Unexpected timing results with file I/O References: <13qeb3upn3qic61@corp.supernews.com> Message-ID: On Feb 4, 10:17 am, Steven D'Aprano wrote: > After reading an earlier thread about opening and closing lots of files, > I thought I'd do a little experiment. > > Suppose you have a whole lot of files, and you need to open each one, > append a string, then close them. There's two obvious ways to do it: > group your code by file, or group your code by procedure. > > # Method one: grouped by file. > for each file: > open the file, append the string, then close it > > # Method two: grouped by procedure. > for each file: > open the file > for each open file: > append the string > for each open file: > close the file > > If you have N files, both methods make the same number of I/O calls: N > opens, N writes, N closes. Which is faster? > > Intuitively, the first method has *got* to be faster, right? It's got one > loop instead of three and it doesn't build an intermediate list of open > file objects. It's so *obviously* going to be faster that it is hardly > worth bothering to check it with timeit, right? > > Well, I wouldn't be writing unless that intuitive result was wrong. So > here's my test results: > > Method 1: > > >>> import timeit > >>> names = ['afile' + str(n) for n in range(1000)] > >>> T = timeit.Timer('''for name in names: > > ... fp = open(name, 'a'); fp.write('xyz\\n'); fp.close() > ... ''', 'from __main__ import names')>>> min(T.repeat(6, 500)) > > 17.391216039657593 > > Method 2: > > >>> for name in names: # reset the files to an empty state. > > ... fp = open(name, 'w'); fp.close() > ...>>> T = timeit.Timer('''files = [open(name, 'a') for name in names] > > ... for fp in files: > ... fp.write('xyz\\n') > ... for fp in files: > ... fp.close() > ... ''', '''from __main__ import names''')>>> min(T.repeat(6, 500)) > > 16.823362112045288 > > Surprisingly, Method 2 is a smidgen faster, by about half a second over > 500,000 open-write-close cycles. It's not much faster, but it's > consistent, over many tests, changing many of the parameters (e.g. the > number of files, the number of runs per timeit test, etc.). > > I'm using Linux and Python 2.5. > > So, what's going on? Can anyone explain why the code which does more work > takes less time? > > -- > Steven The code that does more work takes more time. The second one does quite a bit less work. Think of it like this: You have 500,000 people to fit through a door. Here are your options: 1. For each person, open the door, walk through the door, then close the door. 2. Open the door, allow everyone to walk through, then close the door. Which one would you say would be a more efficient way to fit 500,000 people through the door? From fetchinson at googlemail.com Thu Feb 7 20:26:10 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Thu, 7 Feb 2008 17:26:10 -0800 Subject: Microsoft's challenger to Python In-Reply-To: References: <47AB9D50.5050503@bmm.com> <880dece00802071708m618a8750w5f5709c57ec0ec59@mail.gmail.com> Message-ID: > > > I am not, however, an in depth language nutter, so would > > > appreciate any of our more learned readers comments. Maybe I'm missing the obvious here, but what does Cobra have to do with Microsoft? (Apart from being .NET oriented.) It seems it's an open source project of a guy who doesn't work for Microsoft. From siona at chiark.greenend.org.uk Fri Feb 15 06:17:03 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 15 Feb 2008 11:17:03 +0000 (GMT) Subject: How to tell if I'm being run from a shell or a module References: <44e07112-e3f5-4446-8522-24c2476efd4a@e10g2000prf.googlegroups.com> <9ec4f650-38bb-43e6-a78e-e0b4f1b658dc@e6g2000prf.googlegroups.com> Message-ID: Gabriel Genellina wrote: >a) See if the __main__ module has a __file__ attribute. >b) See if sys.stdin is a real tty c) See if sys.argv[0] != '' (Although this works for the command line interactive shell, I've a suspicion it will fail with IDLE. But I don't have IDLE to hand to check.) -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From lists at cheimes.de Thu Feb 7 10:55:48 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 07 Feb 2008 16:55:48 +0100 Subject: Is there a way to use .NET DLL from Python In-Reply-To: <2298129a-3ca5-41f9-86ed-28805397fd54@f47g2000hsd.googlegroups.com> References: <85706ba0-8c24-4324-9a79-98c97fc802db@e4g2000hsg.googlegroups.com> <6c2845aa-aec5-4b75-852a-551b9cd1d6ab@f10g2000hsf.googlegroups.com> <5845a12f-41dd-4bb3-8684-483e93f55c5f@e25g2000prg.googlegroups.com> <5cbdc3cf-cb84-49e5-b746-2eca0feeb97d@i7g2000prf.googlegroups.com> <2298129a-3ca5-41f9-86ed-28805397fd54@f47g2000hsd.googlegroups.com> Message-ID: Luis M. Gonz?lez wrote: > Oh, I know what you mean. > But that was exactly the reason for having a .DLLs folder, isn't it? > When you place an assembly into this folder, you avoid having to write > this boilerplate code, and simply import the assembly as you would > with a normal python module. At least, that?s how it worked in > previous versions... In IronPython and with PythonDotNET you can import namespaces. Assembly names and name spaces don't have to be related. E.g. ClassLibrary1.dll may provide the namespace ClassLibA and ClassLibB. clr.AddReference('ClassLibrary1') loads the assembly 'ClassLibrary1' and makes all namespaces available to Python. Christian From bearophileHUGS at lycos.com Tue Feb 12 14:49:11 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 12 Feb 2008 11:49:11 -0800 (PST) Subject: IronPython vs CPython: faster in 1.6 times? References: <52c34392-5c5b-49b8-8c75-ba9add438b73@k39g2000hsf.googlegroups.com> Message-ID: <90aad0a7-1393-402c-9dde-5b08e089aeba@i29g2000prf.googlegroups.com> Fuzzyman: > Another interesting little benchmark of CPython and IronPython. Can't > see the code, but it looks like an implementation of the 11 queens > problem and IronPython comes out a clear winner on this one. (Looks > like no benchmark for psyco.) If you want a more reliable set of benchmarks, take all the shootout benchmarks, and try them on IronPython on dotnet, on CPython and on Psyco. Bye, bearophile From http Fri Feb 1 17:29:43 2008 From: http (Paul Rubin) Date: 01 Feb 2008 14:29:43 -0800 Subject: bags? 2.5.x? References: Message-ID: <7xtzkscnu0.fsf@ruckus.brouhaha.com> Dan Stromberg writes: > > * Is the feature useful for the broad mass? > > Yes, probably, at least if this kind of feature's inclusion in other > languages and my two recent needs for it are any indication. In other > languages, they are sometimes called bags or multisets. I use defaultdict(int) all the time, but it's been fairly rare to want to do set operations (union, intersection, difference) on these. I'm not even sure what the intersection should mean. From deets at nospam.web.de Wed Feb 20 03:12:38 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 20 Feb 2008 09:12:38 +0100 Subject: What's "the standard" for code docs? In-Reply-To: <3878093e-e723-47f9-a7e3-fcfca012fa74@n77g2000hse.googlegroups.com> References: <47b69581$0$36393$742ec2ed@news.sonic.net> <96fc10f7-06fd-4e77-b38c-ec63e9b19341@s12g2000prg.googlegroups.com> <3878093e-e723-47f9-a7e3-fcfca012fa74@n77g2000hse.googlegroups.com> Message-ID: <6225nvF21akrdU1@mid.uni-berlin.de> > Are people really writing pure HTML snippets in docstrings to document > each module/class/method? For anything other than a toy project? > > One of the main reasons I'm considering moving to epydoc + reST is > precisely because it's very un-HTML. > > Mind you I want to be able to produce HTML format docs from the > source, but I don't want to actually *put* HTML anywhere near my > precious sources. In the Java-world it *is* pure HTML snipplets... but no, not in python. Diez From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Feb 14 03:18:35 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 14 Feb 2008 09:18:35 +0100 Subject: Cannot understand error message In-Reply-To: <13r72j1nbla1fb3@corp.supernews.com> References: <13r72j1nbla1fb3@corp.supernews.com> Message-ID: <47b3f920$0$11844$426a74cc@news.free.fr> Steven D'Aprano a ?crit : > On Wed, 13 Feb 2008 17:29:59 +0000, Bill Davy wrote: > >> The following code produces an error message (using Idle with Py 2.4 and >> 2.5). "There's an error in your program: EOL while scanning >> single-quoted string". It comes just after "s = ''" (put there to try >> and isolate the broken string). >> >> It would be good if the error message pointed me to the start of said >> single quoted string. > > You know what would also be good? If you didn't expect people to read > over 500 lines of code to find YOUR problem, because you can't be > bothered to isolate the error. > > When you have a problem, send the SMALLEST piece of code the exhibits the > problem, not the entire application. And *please* post the *full* traceback. From aahz at pythoncraft.com Wed Feb 27 15:42:39 2008 From: aahz at pythoncraft.com (Aahz) Date: 27 Feb 2008 12:42:39 -0800 Subject: Article of interest: Python pros/cons for the enterprise References: <3b3111d3-699d-4f8d-b99e-87a0666f60a7@b29g2000hsa.googlegroups.com> Message-ID: In article <3b3111d3-699d-4f8d-b99e-87a0666f60a7 at b29g2000hsa.googlegroups.com>, Carl Banks wrote: >On Feb 24, 7:03 pm, a... at pythoncraft.com (Aahz) wrote: >> In article , >> Jeff Schwab wrote: >>> >>>(3) Garbage collection is at least as desirable a language feature as >>>deterministic destruction. >> >> Enh. There probably are some people who claim that, but I can't think >> of any off-hand. > >I am most certainly claiming it; in fact I'm claiming that GC far more >desirable, because the cost of deterministic destruction is too high. I'm trimming the rest of your post because I don't have time to argue with you, but I want to point out that you're making the same mistake that Jeff is: garbage collection and deterministic destruction are not the only techniques for managing memory and resources. In particular, CPython primarily relies on reference counting, which has similarities with *both* GC and deterministic destruction. Now you know why I said that I don't know anybody who makes Jeff's claim. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "All problems in computer science can be solved by another level of indirection." --Butler Lampson From michael.pearmain at tangozebra.com Tue Feb 12 08:52:57 2008 From: michael.pearmain at tangozebra.com (Mike P) Date: Tue, 12 Feb 2008 05:52:57 -0800 (PST) Subject: CSV Reader References: <43a3a0d8-9425-4bc5-90d3-894fe980d3f7@s19g2000prg.googlegroups.com> <4b1e691a-53ff-4cee-8e15-5bf17f2b56ef@i12g2000prf.googlegroups.com> <5f18e754-ea46-4924-a2cd-3e0869c42455@h11g2000prf.googlegroups.com> Message-ID: <22ac976c-5454-4176-a9b7-789396315dde@z17g2000hsg.googlegroups.com> Hi Chris that's exactley what i wanted to do, Many thanks From jr9445 at ATT.COM Thu Feb 7 16:07:19 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Thu, 7 Feb 2008 15:07:19 -0600 Subject: Why not a Python compiler? In-Reply-To: <87tzkko6dv.fsf@physik.rwth-aachen.de> References: <28eead2f-a40c-414b-bd3d-a941f8a851a2@d70g2000hsb.googlegroups.com><7da40f42-f64f-4939-a0dc-d24d1ff85f2d@v4g2000hsf.googlegroups.com><13qjktdbe76da00@corp.supernews.com><13qmp56btnr55a4@corp.supernews.com> <87tzkko6dv.fsf@physik.rwth-aachen.de> Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of Torsten Bronger > Sent: Thursday, February 07, 2008 3:32 PM > To: python-list at python.org > Subject: Re: Why not a Python compiler? > > > > > I wonder if George Lucas intended it as a joke or if he thought > > a parsec was a unit of time. > > The latter because it was corrected in the novelization. > Errr... didn't one of the novels explain it away by describing the kessel run as a region of space warped by black holes or other objects? Bragging rights for crossing such a field thus centered on shortest distance instead of time. ***** The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA623 From bockman at virgilio.it Mon Feb 4 10:19:28 2008 From: bockman at virgilio.it (bockman at virgilio.it) Date: Mon, 4 Feb 2008 07:19:28 -0800 (PST) Subject: Python GUI toolkit References: Message-ID: <42c7d139-3520-4d73-85cd-f67e3bdacd5a@c4g2000hsg.googlegroups.com> > > Another toolkit you might look into is Tkinter. I think it is something > like the "official" toolkit for python. I also think it is an adapter > for other toolkits, so it will use gtk widgets on gnome, qt widgets on > kde and some other strange widgets on windows. > Not t so, AFAIK. Tkinter is the python adapter for Tk, the toolkit originally developed for Tcl language. The latest version of Tk (not yet integrated in Python, maybe in 2.6) has themes, which emulates the look-and-feel of native toolkit at list for XP and OS X. For unix, the last time I checked, there was only a theme that looked like a plainer version of Gtk default theme. No Gnome or Kde themes yet. The latest version of Tk also increased the set of available widgets, which now is similar to the set of widgets offered by Qt/Gtk.. However, how much of these widgets will be available through Tkinter will depend on people stepping in and upgrading Tkinter beyond simpy ensuring that the old widgets still works. Given that many GUI- developing python programmers have moved to other toolkits, I'm not sure this will ever happen. Ciao -------- FB From fetchinson at googlemail.com Fri Feb 1 01:18:35 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Thu, 31 Jan 2008 22:18:35 -0800 Subject: dict comprehension In-Reply-To: <47A2B7BC.3010406@islandtraining.com> References: <47A2B7BC.3010406@islandtraining.com> Message-ID: > > Hi folks, > > > > There is a withdrawn PEP about a new syntax for dict comprehension: > > http://www.python.org/dev/peps/pep-0274/ which says: > > > > "Substantially all of its benefits were subsumed by generator > > expressions coupled with the dict() constructor." > > > > What does the author mean here? What's the Preferably One Way (TM) to > > do something analogous to a dict comprehension? > > > See about generator expressions in > http://www.python.org/doc/2.4/whatsnew/node4.html. > > The dict builtin can build a dictionary from a list (or iterator or > generator creating a list) of tuples. Put them together and get what > you might be tempted to call a dictionary comprehension. For instance: > > >>> dict((i,i*i) for i in range(10)) > {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81} Neat! From celoserpa at gmail.com Fri Feb 1 13:56:26 2008 From: celoserpa at gmail.com (Marcelo de Moraes Serpa) Date: Fri, 1 Feb 2008 16:56:26 -0200 Subject: What does % mean/does in this context? Message-ID: <1e5bcefd0802011056m11405696t9e64fb53cc479fe4@mail.gmail.com> Take the following piece of code: for item in cart.values(): v = _button_cart % {"idx": idx, "itemname": item.name, "amount": item.cost, "quantity": item.quantity,} cartitems.append(v) What does the % operator is doing there? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Sat Feb 2 10:42:22 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 02 Feb 2008 09:42:22 -0600 Subject: string split without consumption In-Reply-To: References: Message-ID: <47A48F5E.60903@tim.thechases.com> >>> this didn't work elegantly as expected: >>> >>> >>> ss >>> 'owi\nweoifj\nfheu\n' >>> >>> re.split(r'(?m)$',ss) >>> ['owi\nweoifj\nfheu\n'] >> Do you have a need to use a regexp? > > I'd like the general case - split without consumption. I'm not sure there's a one-pass regex solution to the problem using Python's regex engine. If pre-processing was allowed, one could do it. >>>>> ss.splitlines(True) >> ['owi\n', 'weoifj\n', 'fheu\n'] >> > > thanks. Yet this does not work "naturally" consistent in my line > processing algorithm - the further buffering. Compare e.g. > ss.split('\n') .. well, one can do >>> [line + '\n' for line in ss.splitlines()] ['owi\n', 'eoifj\n', 'heu\n'] >>> [line + '\n' for line in (ss+'xxx').splitlines()] ['owi\n', 'eoifj\n', 'heu\n', 'xxx\n'] as another try for your edge case. It's understandable and natural-looking -tkc From bbxx789_05ss at yahoo.com Fri Feb 15 17:24:19 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Fri, 15 Feb 2008 14:24:19 -0800 (PST) Subject: sockets -- basic udp client Message-ID: My question pertains to this example: #!/usr/bin/env python import socket, sys, time host = sys.argv[1] textport = sys.argv[2] s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: port = int(textport) except ValueError: # That didn't work. Look it up instread. port = socket.getservbyname(textport, 'udp') s.connect((host, port)) print "Enter data to transmit: " data = sys.stdin.readline().strip() s.sendall(data) s.shutdown(1) print "Looking for replies; press Ctrl-C or Ctrl-Break to stop." while 1: buf = s.recv(2048) if not len(buf): break print "Received: %s" % buf As far as I can tell, the if statement: if not len(buf): break does nothing. Either recv() is going to read some data or it's going to block. My understanding is that udp sockets do not have a connection, so the server can't close the connection--hich would cause a blank string to be sent to the client. So, as far as I can tell, the only way that code would make sense is if the server were programmed to send a blank string to the client after it sent data to the client. Is that correct? From steve at REMOVE-THIS-cybersource.com.au Sat Feb 9 06:56:56 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 09 Feb 2008 11:56:56 -0000 Subject: which one is more efficient References: <54d22985-9353-4289-9179-6ce17406ca10@l16g2000hsh.googlegroups.com> Message-ID: <13qr588id5srvd3@corp.supernews.com> On Sat, 09 Feb 2008 02:08:15 -0800, bearophileHUGS wrote: > The new string search done by Effbot is really good :-) Care to explain what "new string search" you're referring to? Inquiring minds want to know. -- Steven From deets at nospam.web.de Mon Feb 11 16:08:20 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 11 Feb 2008 22:08:20 +0100 Subject: Sending Python statement over socket in chunks In-Reply-To: References: Message-ID: <61brq4F1u710bU1@mid.uni-berlin.de> Jeffrey Barish schrieb: > I have a python module that contains an assignment statement binding a long > list of things to a name: > > list_of_things = [thing1, thing2, ...] > > where each thing instantiates class Thing when executed. I send this > statement through a socket to a remote module that executes it. The > problem is that it takes too long to send the entire statement. > Accordingly, I am thinking of a solution that sends the list in chunks. > The client then executes each chunk and reassembles the complete list. > Thus, I would first send something like: > > chunk = [thing1, thing2, ... thing10] > > and then > > chunk = [thing11, thing12, ... thing20] > > until all things have been transmitted. At the client end, I would execute > each chunk statement and then do > > list_of_things.append(chunk) > > The point of this solution is that I can start doing useful work in the > client as soon as I receive the first chunk, and the others can arrive in > the background and be available by the time I need them. > > One way I could implement this solution is to execute the statement for the > entire list_of_things in the server and then create chunk = [...] > statements with the lists filled using the repr of the class. I believe > that this solution will work, but it seems a shame to execute the > list_of_things statement in the server rather than have the server stupidly > handle strings (because executing the statement takes time and because the > server currently doesn't understand "Thing"). Should I investigate using a > parser to carve up the list_of_things = [...] statement? Basically, I just > need to identify each Thing(...) expression and then count out some number > of them. I should be able to do that using re. Or perhaps I should write > my own parser using Python string operations as all I need to do is count > out some number of Things delimited by "Thing(" at one end and "),\nThing(" > at the other (or ")]\n" at the end of the list). Did I just answer my own > question? > > Of course, I need to balance the complexity of any alternative solution > against simply executing the statement on the server. Stop reinventing the wheel, start using pyro. Then either return the list as whole, or if it _really_ is to big, return subsequent slices of it. Diez From bkamrani at gmail.com Mon Feb 25 07:18:19 2008 From: bkamrani at gmail.com (bkamrani at gmail.com) Date: Mon, 25 Feb 2008 04:18:19 -0800 (PST) Subject: print help content in a Command Prompt References: <4f2909d7-df2a-442c-bc43-5ecc04e1ad14@q78g2000hsh.googlegroups.com> Message-ID: On Feb 25, 12:59 pm, Necmettin Begiter wrote: > 25 February 2008 Monday 11:15:14 tarihinde bkamr... at gmail.com ?unlar? yazm??t?: > > > Hi, > > This is a basic problem, but I want to print help content in a Command > > Prompt in WinXP and scrolling back to see the first lines. If I start > > a command prompt and run python, and then for example, > > > >>> help(list) > > > it starts showing the help, which can be controlled by page or raw > > using Spacebar or Enter but after this ends, it seems that I can't > > scroll back to see again the first lines. > > In the Command Prompt Properties, layout tab, my Screen buffer size > > is Width:80, Height:3000 and windows size 80x40 (W&H). > > > Any idea...? thanks in advance!! > > /Ben > > Try PgUp when in Python help view. > > Try "python -c 'help(list)'" to get the help without Python prompt. Even this doesn't help. But I think I've found a reason for this. If I change the "start in" directory to C:\WINDOWS\system32\ (this is where the cmd.exe file is located), then the printed text doesn't get hide. Don't ask me why... Thanks anyway, /Ben From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Feb 12 04:30:39 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 12 Feb 2008 10:30:39 +0100 Subject: callback send data to webpage In-Reply-To: <2008021200112816807-invalid@domainmail> References: <2008021200112816807-invalid@domainmail> Message-ID: <47b1670f$0$12982$426a34cc@news.free.fr> Will a ?crit : > I have a small python script with a callback in it that receives data > from another app. Everytime the callback gets data, I'd like to send it > into a webpage w/o refreshing the entire webpage. > > Anyone know of a tutorial that would help do that? > The best thing to do would be to learn how HTTP works. Then have a look at Ajax and Comet: http://en.wikipedia.org/wiki/Comet_%28programming%29 http://cometd.com/ http://www.irishdev.com/NewsArticle.aspx?id=2166 From micah at cowan.name Tue Feb 26 13:05:48 2008 From: micah at cowan.name (Micah Cowan) Date: Tue, 26 Feb 2008 10:05:48 -0800 Subject: network programming: how does s.accept() work? In-Reply-To: <87d4qjvrtt.fsf@mulj.homelinux.net> References: <6d564fca-3884-4665-8a86-f7e658217a33@e60g2000hsh.googlegroups.com> <446482ef-1fd8-41dc-a8fd-44de8b51a8e8@o10g2000hsf.googlegroups.com> <379fcee4-15e0-48c2-863b-4b7458893cbe@h25g2000hsf.googlegroups.com> <711155c0-1305-41d3-895c-af9b8fe66f21@j28g2000hsj.googlegroups.com> <87d4qjvrtt.fsf@mulj.homelinux.net> Message-ID: Hrvoje Niksic wrote: > 7stud writes: > >> When you surf the Web, say to http://www.google.com, your Web browser >> is a client. The program you contact at Google is a server. When a >> server is run, it sets up business at a certain port, say 80 in the >> Web case. It then waits for clients to contact it. When a client does >> so, the server will usually assign a new port, say 56399, specifically >> for communication with that client, and then resume watching port 80 >> for new requests. > > Actually the client is the one that allocates a new port. All > connections to a server remain on the same port, the one it listens > on: (Hey, I know you! ;) ) Right. 7stud, what you seem to be missing, and what I'm not sure if anyone has clarified for you (I have only skimmed the thread), is that in TCP, connections are uniquely identified by a /pair/ of sockets (where "socket" here means an address/port tuple, not a file descriptor). It is fine for many, many connections, using the same local port and IP address, so long as the other end has either a different IP address _or_ a different port. There is no issue with lots of processes sharing the same socket for various separate connections, because the /pair/ of sockets is what identifies them. See the "Multiplexing" portion of section 1.5 of the TCP spec (http://www.ietf.org/rfc/rfc0793.txt). Reading some of what you've written elsewhere on this thread, you seem to be confusing this address/port stuff with what accept() returns. This is hardly surprising, as unfortunately, both things are called "sockets": the former is called a socket in the various RFCs, the latter is called a socket in documentation for the Berkeley sockets and similar APIs. What accept() returns is a new file descriptor, but the local address-and-port associated with this new thing is still the very same ones that were used for listen(). All the incoming packets are still directed at port 80 (say) of the local server by the remote client. It's probably worth mentioning at this point, that while what I said about many different processes all using the same local address/port combination is true, in implementations of the standard Berkeley sockets API the only way you'd _arrive_ at that situation is that all of those different connections that have the same local address/port combination is that they all came from the same listen() call (ignoring mild exceptions that involve one server finishing up connections while another accepts new ones). Because while one process has a socket descriptor bound to a particular address/port, no other process is allowed to bind to that combination. However, for listening sockets, that one process is allowed to accept many connections on the same address/port. It can handle all those connections itself, or it can fork new processes, or it can pass these connected sockets down to already-forked processes. But all of them continue to be bound to the same local address-and-port. Note that, if the server's port were to change arbitrarily for every successful call to accept(), it would make it much more difficult to filter and/or analyze TCP traffic. If you're running, say, tcpdump, the knowledge that all the packets on a connection that was originally directed at port 80 of google.com, will continue to go to port 80 at google.com (even though there are many, many, many other connections out there on the web from other machines that are all also directed at port 80 of google.com), is crucial to knowing which packets to watch for while you're looking at the traffic. -- HTH, Micah J. Cowan Programmer, musician, typesetting enthusiast, gamer... http://micah.cowan.name/ From mccredie at gmail.com Thu Feb 7 10:27:26 2008 From: mccredie at gmail.com (Matimus) Date: Thu, 7 Feb 2008 07:27:26 -0800 (PST) Subject: beginners help References: <47aaffb2$0$85781$e4fe514c@news.xs4all.nl> Message-ID: <383cce14-62ce-4e38-8500-c2a1f3c2e1da@z17g2000hsg.googlegroups.com> On Feb 7, 7:53 am, Guido van Brakel wrote: > Hello > > I totally new to python and i'm doing a python course now. Maybe someone > could help me a little bit here: > > I need to create this script. > > If i enter a center digit like 5 for example i need to create two > vertical and horzitonal rows that looks like this. If i enter 6 it shows > 6 six starts. How can i do this, because i don't have any clue. > > ***** > * * > * * > * * > ***** > > Kind Regards, > > -- > Guido van Brakel > -- If you turn this in you will be rewarded for your effort :) [code] side = input("How many stars on a side?:") if side == 5: print "*****" print "* *" print "* *" print "* *" print "*****" elif side == 6: print "******" print "* *" print "* *" print "* *" print "* *" print "******" [/code] From shore.cloud at gmail.com Sun Feb 24 10:31:17 2008 From: shore.cloud at gmail.com (Mr Shore) Date: Sun, 24 Feb 2008 07:31:17 -0800 (PST) Subject: mapping problem References: <04886f27-d234-4aa9-8ca4-5e720bf88a54@s19g2000prg.googlegroups.com> <13rdf3fggdreb91@corp.supernews.com> Message-ID: <211b08fa-b968-4c70-917e-76716b7fc153@28g2000hsw.googlegroups.com> On Feb 16, 6:35?pm, Steven D'Aprano wrote: > On Sat, 16 Feb 2008 01:35:32 -0800,MrShorewrote: > > I've now crawled the meta infor,but with multi name all means the same > > thing, > > such as MS,microsoft,microsoft corporation all means the same thing, how > > can I mapping words like this to the same thing? > > The same way you would map anything: use a dict. > > You know, sometimes I'm astounded by the ability of the human brain to > find semantic meaning in what is grammatically and syntactically > gibberish. Most of the words are English, but putting them all together > makes no sense. And yet, by interpolating between key words, I can guess > that the poster wants something like this: > > mapping = {"MS": "Microsoft", "Microsoft": "Microsoft", > "Microsoft Corporation": "Microsoft"} > > If I have guessed poorly, could you please try again, more carefully? If > you're not a native English speaker, please say so and we'll make > allowances, and if you are a native English speaker with no cognitive > disabilities, you should be ashamed of wasting our time with such poor > communication. > > -- > Steven > who is unapologetic for being grumpy about the oxygen-thieves using the > Internet these days, and if that makes me a curmudgeon, so be it. in fact what I expected is a solution which can automatically do the job maybe something related with artificial intelligence but seems feasible to do it manually thx for all and pre say sorry if my english once again caused your uncomfortable in understanding. From bignose+hates-spam at benfinney.id.au Sun Feb 10 17:50:07 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 11 Feb 2008 09:50:07 +1100 Subject: Turn off ZeroDivisionError? References: <63d2e7d1-aa26-4ddc-9d12-42ae636104c1@s37g2000prg.googlegroups.com> <13qunlu5nrva731@corp.supernews.com> Message-ID: <877ihc5sv4.fsf@benfinney.id.au> Mark Dickinson writes: > On Feb 10, 3:29?pm, Grant Edwards wrote: > > platform does". ?Except it doesn't in cases like this. All my > > platforms do exactly what I want for division by zero: they > > generate a properly signed INF. ?Python chooses to override > > that (IMO correct) platform behavior with something surprising. > > Python doesn't generate exceptions for other floating point > > "events" -- why the inconsistency with divide by zero? > > But not everyone wants 1./0. to produce an infinity; some people > would prefer an exception. Special cases aren't special enough to break the rules. Most people would not want this behaviour either:: >>> 0.1 0.10000000000000001 But the justification for this violation of surprise is "Python just does whatever the underlying hardware does with floating-point numbers". If that's the rule, it shouldn't be broken in the special case of division by zero. -- \ ?If the desire to kill and the opportunity to kill came always | `\ together, who would escape hanging?? ?Mark Twain, _Following | _o__) the Equator_ | Ben Finney From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Feb 29 10:29:16 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 29 Feb 2008 16:29:16 +0100 Subject: joining strings question In-Reply-To: <6b41eaf1-05e1-4b04-8c31-6737166f267f@b1g2000hsg.googlegroups.com> References: <6b41eaf1-05e1-4b04-8c31-6737166f267f@b1g2000hsg.googlegroups.com> Message-ID: <47c82437$0$15299$426a74cc@news.free.fr> patrick.waldo at gmail.com a ?crit : > Hi all, > > I have some data with some categories, titles, subtitles, and a link > to their pdf and I need to join the title and the subtitle for every > file and divide them into their separate groups. > > So the data comes in like this: > > data = ['RULES', 'title','subtitle','pdf', > 'title1','subtitle1','pdf1','NOTICES','title2','subtitle2','pdf','title3','subtitle3','pdf'] > > What I'd like to see is this: > > [RULES', 'title subtitle','pdf', 'title1 subtitle1','pdf1'], > ['NOTICES','title2 subtitle2','pdf','title3 subtitle3','pdf'], etc... I don't know where your data come from, but the data structure is obviously wrong. It should at least be a list of tuples, ie: data = [ ('RULES', [ ('title', 'subtitle', 'pdf'), ('title1', 'subtitle1', 'pdf1') ] ), ('NOTICES',[ ('title2','subtitle2','pdf',) ('title3','subtitle3','pdf') ] ), ] > I've racked my brain for a while about this and I can't seem to figure > it out. Any ideas would be much appreciated. If possible, fix the code generating the dataset. Any other solution will be at best a dirty - and brittle - hack. From qgallet at gmail.com Sun Feb 24 06:35:32 2008 From: qgallet at gmail.com (Quentin Gallet-Gilles) Date: Sun, 24 Feb 2008 12:35:32 +0100 Subject: Ruby with Netbeans question! In-Reply-To: <8763e288-6f69-4293-bb5b-8f5ff5132747@c33g2000hsd.googlegroups.com> References: <8763e288-6f69-4293-bb5b-8f5ff5132747@c33g2000hsd.googlegroups.com> Message-ID: <8b943f2b0802240335m7c379c7bhe82fd59f80f55fd3@mail.gmail.com> Hi Steve, Considering this is a Python list, I doubt you'll get much help for something related to Netbeans and Ruby. You're better off asking questions on the proper list : http://www.netbeans.org/community/lists/ Quentin On Sun, Feb 24, 2008 at 12:26 PM, Steve wrote: > Hi all > Hope I`m ok posting a Netbeans query here?. I`m trying to learn Ruby > using the Netbeans IDE. It seems a pretty slick application but I`m > wondering if its possible to run a prog without creating a `new > project` each time?. I just want to be able to type in a few lines of > code and run it but it keeps running the `main project` which might be > an earlier prog I have written??. I`m sure the solution is staring me > in the face but would be grateful for any tips folk could provide. > Cheers > Steve > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Fri Feb 29 14:09:06 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 29 Feb 2008 13:09:06 -0600 Subject: joining strings question In-Reply-To: References: <6b41eaf1-05e1-4b04-8c31-6737166f267f@b1g2000hsg.googlegroups.com> <281b102e-0533-4357-8bab-9d3247fba719@e25g2000prg.googlegroups.com> Message-ID: <47C85852.5080702@tim.thechases.com> I V wrote: > On Fri, 29 Feb 2008 08:18:54 -0800, baku wrote: >> return s == s.upper() > > A couple of people in this thread have used this to test for an upper > case string. Is there a reason to prefer it to s.isupper() ? For my part? forgetfulness brought on by underuse of .isupper() -tkc From steve at holdenweb.com Sat Feb 23 08:23:01 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 23 Feb 2008 08:23:01 -0500 Subject: n00b with urllib2: How to make it handle cookie automatically? In-Reply-To: References: Message-ID: 7stud wrote: > On Feb 21, 11:50 pm, est wrote: >> class SmartRequest(): >> > > You should always define a class like this: > > class SmartRequest(object): > > > unless you know of a specific reason not to. > > It's much easier, though, just to put __metaclass__ = type at the start of any module where you want exlusively new-style objects. And I do agree that you should use exclusively new-style objects without a good reason for not doing, though thanks to Guido's hard work it mostly doesn't matter. $ cat test94.py __metaclass__ = type class Rhubarb: pass rhubarb = Rhubarb() print type(Rhubarb) print type(rhubarb) $ python test94.py regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From castironpi at gmail.com Wed Feb 27 23:12:47 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 27 Feb 2008 20:12:47 -0800 (PST) Subject: Place n indistinguishable items into k distinguishable boxes References: Message-ID: On Feb 27, 8:40?pm, Michael Robertson wrote: > Hi, > > I need a generator which produces all ways to place n indistinguishable > items into k distinguishable boxes. > > For n=4, k=3, there are (4+3-1)!/(3-1)!/4! = 15 ways. > > (0,0,4) > (0,4,0) > (4,0,0) > > (0,2,2) > (2,0,2) > (2,2,0) > > (0,1,3) > (0,3,1) > (3,0,1) > (3,1,0) > > (1,1,2) > (1,2,1) > (2,1,1) > > The generator needs to be fast and efficient. > > Thanks. Note that the boxes are indistinguishable, and as such, ( 1, 0, 3 ) == ( 3, 0, 1 ), but != ( 3, 1, 0 ). How so? From rocksportrocker at googlemail.com Wed Feb 27 07:28:53 2008 From: rocksportrocker at googlemail.com (rocksportrocker) Date: Wed, 27 Feb 2008 04:28:53 -0800 (PST) Subject: BaseHTTPServer and do_POST method Message-ID: <6fa9fbde-fc6b-4b4a-a8ec-33bb504b74a5@62g2000hsn.googlegroups.com> Hi, I am trying to implement a local server for storing and retrieving numerical data. So I used BaseHTTPServer as follows: from BaseHTTPServer import * class Handler(BaseHTTPRequestHandler): def do_POST(self): print "POST" self.send_response(200) httpd = HTTPServer(("",8000), Handler) From MartinRinehart at gmail.com Wed Feb 20 07:34:20 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Wed, 20 Feb 2008 04:34:20 -0800 (PST) Subject: Python Memory Manager References: <0c69faf6-c019-425b-b988-fc2b76befd3d@60g2000hsy.googlegroups.com> <7xejbb6zss.fsf@ruckus.brouhaha.com> <7885d6a5-0aa0-4ef5-b409-a954170ae9da@i7g2000prf.googlegroups.com> <2498f088-19e8-4ad7-b353-accb0aca4234@i7g2000prf.googlegroups.com> <7xodab27ps.fsf@ruckus.brouhaha.com> Message-ID: <212ae2ca-7c6f-490b-853d-834c5a062b83@d4g2000prg.googlegroups.com> Paul Rubin wrote: > repz movsw is a pretty lame way to copy data on current x86's. > Use XMM instead. Thank you, Paul. I'm pretty sure you meant MMX, Multi-Media eXtensions. Paul's just told me to upgrade my 32-bit thinking to use newer 64-bit registers, even on a 32-bit cpu. Please divide my prior timings by two. Pentium or later required. From kevin.p.dwyer at gmail.com Wed Feb 6 14:38:28 2008 From: kevin.p.dwyer at gmail.com (kdwyer) Date: Wed, 6 Feb 2008 11:38:28 -0800 (PST) Subject: Broke my IDLE! References: <1e6ec8dc-3fa4-4e75-86c1-26852ea30a65@n20g2000hsh.googlegroups.com> <1603d98e-a543-494d-acfe-e96b76c2fe37@j20g2000hsi.googlegroups.com> Message-ID: <629bead4-a46d-4c71-b4b4-81baad1723ef@f10g2000hsf.googlegroups.com> Just to clarify my earlier comment... IDLE (on Windows, at least) creates a folder called .idlerc in the current directory when it is called. If you amend the key bindings two files, config-keys.cfg and config-main.cfg are created. config- keys.cfg contains the amended key bindings and config-main.cfg contains the name of the key binding file if it is not the platform default. The config processing seems to happen in /Lib/idlelib/ configHandler.py. Sorry for the inaccuracy in the first post, Cheers, Kev From castironpi at gmail.com Wed Feb 27 23:02:59 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 27 Feb 2008 20:02:59 -0800 (PST) Subject: Place n indistinguishable items into k distinguishable boxes References: Message-ID: On Feb 27, 9:31?pm, Michael Robertson wrote: > Michael Robertson wrote the following on 02/27/2008 06:40 PM: > > > I need a generator which produces all ways to place n indistinguishable > > items into k distinguishable boxes. > > I found: > > http://portal.acm.org/citation.cfm?doid=363347.363390 > > Do anyone know if there are better algorithms than this? Or free? From dickinsm at gmail.com Wed Feb 27 00:21:09 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Tue, 26 Feb 2008 21:21:09 -0800 (PST) Subject: How about adding rational fraction to Python? References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> Message-ID: On Feb 26, 11:55?pm, Paul Rubin wrote: > So use: ?return sum(number_list) / float(len(number_list)) > That makes it somewhat more explicit what you want. ?Otherwise But that fails for a list of Decimals... Mark From schlaber at gmail.com Wed Feb 20 09:25:45 2008 From: schlaber at gmail.com (Brot) Date: Wed, 20 Feb 2008 06:25:45 -0800 (PST) Subject: smtplib & gnupg Message-ID: Hello, at the moment my program sends mail with smtplib. Is there a chance to sign and/or encode/cipher this mails with GnuPG? If yes, does anyone have some sample code? Regards Bernd From sj.m at iloinen.net Wed Feb 13 05:09:10 2008 From: sj.m at iloinen.net (Juha S.) Date: Wed, 13 Feb 2008 12:09:10 +0200 Subject: No Module Named pstats Message-ID: <47B2C1C6.5020705@iloinen.net> 2008/2/13, Juha S. >: > > Hi, > > I'm trying to use the Python profilers to test my code, but I get the > following output for cProfile.run() at the interpreter: > > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python2.5/cProfile.py", line 36, in run > result = prof.print_stats(sort) > File "/usr/lib/python2.5/cProfile.py", line 80, in print_stats > import pstats > ImportError: No module named pstats > > > I also tried to use the profile module but I get: > > >>> import profile > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named profile > > > I'm on Ubuntu 7.10 with Python 2.5, and I can't seem to figure out > what's missing. > > > I think you have to install python-profiler. > > Regards, > Ilias Thanks! I apt-get installed the package and now cProfiler works correctly. From aahz at pythoncraft.com Mon Feb 11 14:29:49 2008 From: aahz at pythoncraft.com (Aahz) Date: 11 Feb 2008 11:29:49 -0800 Subject: Pure Python Salsa20 Stream Cipher Implementation References: <6ddc44aa-7c71-4cee-a6db-31dac0402bd6@z17g2000hsg.googlegroups.com> Message-ID: In article , Gabriel Genellina wrote: >En Sat, 09 Feb 2008 20:29:58 -0200, Aahz escribi?: >> In article , >> Gabriel Genellina wrote: >>> En Sat, 09 Feb 2008 01:34:30 -0200, >>> escribi?: >>>> On 8 Feb., 17:18, Paul Rubin wrote: >>>>> >>>>> I don't understand why a pure python version of salsa20 would be >>>>> interesting. Is there some application that uses salsa20, that's >>>>> worth being able to interoperate with in pure python? >>>> >>>> The reason for a pure python is that it would be independent from the >>>> platform. A C implementation is faster, but you need to compile it for >>>> every platform. A python implementation doesn't have that problem and >>>> could be used to fall back upon. >>> >>> On most platforms -with a notable exception- there is a C compiler >>> available as a standard tool, which is used to compile Python itself. >>> distutils can easily compile and install C extensions itself, so most of >>> the time "python setup.py install" is the only thing users have to >>> execute, exactly the same as if the package were pure Python. With >>> setuptools, things may be even easier. >> >> What about Jython, PyPy, and IronPython? > >What about them? >Do you mean that there should be a Python implementation for each and >every imaginable module over there, so it can be used with all of those >Python variants? Restricted of course to their minimum common feature set? Is there some reason you're using exaggerated language? My only point is that simply saying "C compiler! C compiler!" ignores the fact that Python itself is multi-platform (and makes you look foolish); whether any given module should be written in pure Python needs to be decided on a case-by-case basis. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "All problems in computer science can be solved by another level of indirection." --Butler Lampson From duncan.booth at invalid.invalid Tue Feb 19 05:39:26 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 Feb 2008 10:39:26 GMT Subject: Garbage collection References: Message-ID: Jarek Zgoda wrote: > Is that true assumption that __del__ has the same purpose (and same > limitations, i.e. the are not guaranteed to be fired) as Java finalizer > methods? One other point I should have mentioned about __del__: if you are running under Windows and the user hits Ctrl+Break then unless you handle it Python will exit without doing any cleanup at all (as opposed to any other method of exiting such as Ctrl+C). If this matters to you then you can install a signal handler to catch the Ctrl+Break and exit cleanly. From igouy2 at yahoo.com Thu Feb 7 13:17:14 2008 From: igouy2 at yahoo.com (Isaac Gouy) Date: Thu, 7 Feb 2008 10:17:14 -0800 (PST) Subject: IronPython vs CPython: faster in 1.6 times? References: <52c34392-5c5b-49b8-8c75-ba9add438b73@k39g2000hsf.googlegroups.com> <47A8BD65.2090707@behnel.de> <74d6eb8e-7c33-4898-818a-185d04243940@l16g2000hsh.googlegroups.com> <47aa2cb2$0$27196$9b4e6d93@newsspool1.arcor-online.net> Message-ID: On Feb 6, 1:54 pm, Stefan Behnel wrote: > Isaac Gouy wrote: > > On Feb 5, 11:47 am, Stefan Behnel wrote: > >> bearophileH... at lycos.com schrieb: > > >>> Mike C. Fletcher: > >>>> Not sure if Mono also provides a speedup. > >>> There is a set of good benchmarks here, the answer is negative: > >>>http://shootout.alioth.debian.org/sandbox/benchmark.php?test=all?... > >> This doesn't look like Mono to me: > > >> IronPython 1.1 (1.1) on .NET 2.0.50727.42 > > >> Stefan > > > Have you actually looked at the version string from IronPython-1.1- > > Bin.zip running on Mono? > > Why? Would that look like Mono? :) > > Stefan Why? Because then you'd be doing more than expressing your personal ignorance. From jeff at jmcneil.net Thu Feb 14 12:40:23 2008 From: jeff at jmcneil.net (Jeff McNeil) Date: Thu, 14 Feb 2008 12:40:23 -0500 Subject: How to tell if I'm being run from a shell or a module In-Reply-To: <44e07112-e3f5-4446-8522-24c2476efd4a@e10g2000prf.googlegroups.com> References: <44e07112-e3f5-4446-8522-24c2476efd4a@e10g2000prf.googlegroups.com> Message-ID: <82d28c40802140940l4a95daffk26264d289dab1ee0@mail.gmail.com> Check to see what the value of '__name__' is, for example: if __name__ == '__main__': execute_interactive_code() else: I_am_just_a_lowly_module() The value of __name__ will correspond to the name of your module: $ cat a.py print __name__ $ $ python Python 2.5.1 (r251:54863, Oct 30 2007, 13:54:11) [GCC 4.1.2 20070925 (Red Hat 4.1.2-33)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import a a >>> Thanks! Jeff On 2/14/08, dg.google.groups at thesamovar.net wrote: > > Hi all, > > Is there any standard way to tell if the user is running from a module > or from an interactive shell like IDLE or IPython? The best I've come > up with so far is for a function to look at > getouterframes(currentframe())[1][1] (the filename in the frame record > of the frame that called the function), and check if it exists or not > with os.path.exists. IPython gives '(ipython console)' and IDLE gives > 'pyshell#0' whereas running from a module gives its filename. This > seems a bit hacky. Any better ideas? > > -- > Dan Goodman > http://thesamovar.net/contact > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Wed Feb 6 22:17:57 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 6 Feb 2008 19:17:57 -0800 (PST) Subject: Code block function syntax, anonymous functions decorator References: Message-ID: On Feb 6, 8:10?pm, castiro... at gmail.com wrote: > On Feb 6, 5:45?pm, Jean-Paul Calderone wrote: > > > > > > > On Wed, 06 Feb 2008 23:59:27 +0100, "Diez B. Roggisch" wrote: > > > >castiro... at gmail.com schrieb: > > >> def run3( block ): > > >> ? ?for _ in range( 3 ): > > >> ? ? ? block() > > > >> run3(): > > >> ? ?normal_suite() > > > >> Introduces new syntax; arbitrary functions can follow 'colon'. > > > >> Maintains readability, meaning is consistent. > > > >> Equivalent to: > > > >> def run3( block ): > > >> ? ?for _ in range( 3 ): > > >> ? ? ? block() > > > >> @run3 > > >> def anonfunc(): > > >> ? ?normal_suite() > > > >> Simplification in cases in which decorators are use often. > > > >This is non-sensical - how do you invoke anonfunc? They would all bind > > >to the same name, run3. Or to no name as all, as your "spec" lacks that. > > > As he said, the decorator version is the _equivalent_ to the syntax he > > was proposing. ?The point isn't to decorate the function, so perhaps he > > shouldn't have used decorator syntax, but instead: > > > ? ? def anonfunc(): > > ? ? ? ? normal_suite() > > ? ? run3(anonfunc) > > ? ? del anonfunc > > > So it's not non-sensical. ?It's a request for a piece of syntax. > > > >Besides, it's butt-ugly IMHO. But taste comes after proper definition... > > > It's properly defined. ?Not that I'm endorsing this or anything. ?I'd > > rather not see half-assed syntax proposals at all, even if they're super > > great (and some of the syntax that's made it into Python is much worse > > than this). > > > Jean-Paul- Hide quoted text - > > > - Show quoted text - > > Yes. ?@run3( anonfunc ) runs -in-place-. ?Jean-Paul's was a closer > equivalent. > > It's used for a piece of code that won't get called like with > statements.- Hide quoted text - > > - Show quoted text - I know of two examples. Thread starting, and event binding in a framework GUI. Of course, not too much farther along, for X in A as C, storing the code block and/or for loop "object" as a object in "C", and likewise for if. These met with disfavor in another place. start_new_thread( codeblock as target, args= () ): normal_suite() bind( "", codeblock as A ): handle_event( event ) But where does 'event' come from? mybind( "", codeblock as A )( event ): handle_event( event ) ? From pavlovevidence at gmail.com Sat Feb 2 18:45:32 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 2 Feb 2008 15:45:32 -0800 (PST) Subject: Linux Journal Survey References: <1666950d-e9a5-4b7c-a614-5bba90e5b4ca@y5g2000hsf.googlegroups.com> <56eb736f-5ba3-417a-a4c1-3a310a67c3d3@s12g2000prg.googlegroups.com> Message-ID: On Feb 2, 12:03 pm, Albert van der Horst wrote: > In article <56eb736f-5ba3-417a-a4c1-3a310a67c... at s12g2000prg.googlegroups.com>, > > > > Russ P. wrote: > >On Jan 23, 7:42 pm, George Sakkis wrote: > >> On Jan 23, 8:14 pm, dwb... at gmail.com wrote: > > >> > The annual Linux Journal survey is online now for any Linux users who > >> > want to vote for Python. http://www.linuxjournal.com/node/1006101 > > >> ... > > >> 18. What is your favorite programming language? > > >> (15 choices, Python not included) > > >> 19. What is your favorite scripting language? > > >> o Python > > >> o Perl > > >> (5 more choices) > > >> Python is much more than a "scripting language" (whatever this means, > >> other than a semi-derogatory term used by clueless PHBs). Sorry, I'll > >> pass. > > >> George > > >Someone please correct me if I am wrong, but I think of a Python > >"script" as a flat source file with no (or few) functions or classes, > >whereas a full-blown "program" has functions and classes. Both have > >their place. > > >I agree it is unfortunate that the Linux World poll classified Python > >as a "scripting language." I suspect they did that because Python is > >not (typically) compiled and does not have static typing. > > In the context of linux a programming language is > a language that generates an ELF binary executable to be stored > in a /.../bin/ directory. > A scripting language is a language whose programs are normally > distributed in human-readable form. It is appropriate to call > such a program a script. If the first two characters is "#!" > and the execution bit is set, it is a script in the linux sense. > > So as far as I can tell it boils down to a clear technical > distinction, and I'm sure they didn't mean offence. Java doesn't compile to ELF binaries, last time I checked. Carl Banks From fuzzyman at gmail.com Wed Feb 6 16:42:20 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Wed, 6 Feb 2008 13:42:20 -0800 (PST) Subject: IronPython vs CPython: faster in 1.6 times? References: <52c34392-5c5b-49b8-8c75-ba9add438b73@k39g2000hsf.googlegroups.com> Message-ID: <64db21e0-005a-4fd5-b14c-1d8a9458fb27@i72g2000hsd.googlegroups.com> On Feb 5, 6:52 pm, Steve Holden wrote: > Jeff wrote: > >IronPythonruns on top of .NET. I would be suspect of any claims that > > it is faster than cPython, just as I would of claims that Stackless or > > Jython are faster. > > Well don't be. There are benchmarks that clearly showIronPythonas > faster for selected tests. Other tests show CPython running more quickly. > This has been our experience at Resolver Systems. Code that makes heavy use of function calls, non-exceptional exception handling or arithmetic tends to run faster whereas the built-in types tend to be slower. It makes profiling code for optimisation all the more important because all your usual assumptions about Python performance tend to be wrong... Michael Foord http://www.manning.com/foord > As always, a benchmark is only really valuable on a typical workload for > the intended application. > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC http://www.holdenweb.com/ From cwitts at gmail.com Thu Feb 14 01:21:22 2008 From: cwitts at gmail.com (Chris) Date: Wed, 13 Feb 2008 22:21:22 -0800 (PST) Subject: Cannot understand error message References: <13r72j1nbla1fb3@corp.supernews.com> Message-ID: <1926627d-b604-4d8a-9717-61353b76267e@m78g2000hsh.googlegroups.com> On Feb 14, 2:25 am, Steven D'Aprano wrote: > On Wed, 13 Feb 2008 17:29:59 +0000, Bill Davy wrote: > > The following code produces an error message (using Idle with Py 2.4 and > > 2.5). "There's an error in your program: EOL while scanning > > single-quoted string". It comes just after "s = ''" (put there to try > > and isolate the broken string). > > > It would be good if the error message pointed me to the start of said > > single quoted string. > > You know what would also be good? If you didn't expect people to read > over 500 lines of code to find YOUR problem, because you can't be > bothered to isolate the error. > > When you have a problem, send the SMALLEST piece of code the exhibits the > problem, not the entire application. You can't rely on Chris (who > apparently has no life, no offense intended Chris) being around all the > time. > > -- > Steven Hehe, no offense taken Steven. :p From joshua.r.english at gmail.com Mon Feb 18 13:23:28 2008 From: joshua.r.english at gmail.com (Josh English) Date: Mon, 18 Feb 2008 10:23:28 -0800 Subject: Developing a Package with Sub Packages In-Reply-To: References: Message-ID: When testing the package in idle, this results in C:\Python25\Lib\idlelib instead of the file. The Data folder is created in this folder now. On 2/18/08, Gabriel Genellina wrote: > En Sun, 17 Feb 2008 22:34:27 -0200, Josh English > escribi?: > > > Here's what I think is happening: IMS/__init__.py uses os.getcwd() to > > establish the path to the data folder and the files inside of it. When > > I run StoryCreator, os.getcwd() returns the story folder. > > If I'm right, how can I get the IMS/__init__.py module to use relative > > paths to its own module, and not the current working directory the os > > module provides? > > Use the module's own __file__ attribute: > my_path = os.path.abspath(os.path.dirname(__file__)) > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list -- Josh English Joshua.R.English at gmail.com http://joshenglish.livejournal.com From http Mon Feb 25 02:04:14 2008 From: http (Paul Rubin) Date: 24 Feb 2008 23:04:14 -0800 Subject: How about adding rational fraction to Python? References: <70ecaf16-7308-455f-9048-730b2b2f9f2f@p43g2000hsc.googlegroups.com> <13rf9tvbkt66r2a@corp.supernews.com> <198927a7-9478-42b3-a972-82049f0130ac@u10g2000prn.googlegroups.com> <1bc9bba7-dc7f-4cfe-8e1c-fa5901c9f556@n77g2000hse.googlegroups.com> <97f30679-483d-4751-9a6e-0858b36eb426@d4g2000prg.googlegroups.com> <649ac8a9-ae09-4e9b-85c2-f37043af21fd@28g2000hsw.googlegroups.com> <0d1955fc-762c-44e1-a5d8-372c71458455@p25g2000hsf.googlegroups.com> <36204e6f-0d82-449b-8ca5-c819ace9a55a@p73g2000hsd.googlegroups.com> Message-ID: <7xy799v7o1.fsf@ruckus.brouhaha.com> Carl Banks writes: > Try doing numerical integration sometime with rationals, and tell me > how that works out. Try calculating compound interest and storing > results for 1000 customers every month, and compare the size of your > database before and after. Usually you would round to the nearest penny before storing in the database. From DustanGroups at gmail.com Sat Feb 9 07:34:46 2008 From: DustanGroups at gmail.com (Dustan) Date: Sat, 9 Feb 2008 04:34:46 -0800 (PST) Subject: Edit Python code programmatically References: <47AD90B5.9030504@gmail.com> Message-ID: On Feb 9, 6:10 am, Alex wrote: > Guilherme Polo wrote: > > 2008/2/9, Alex : > > >> Which library could you recommend to perform simple editing of Python > >> code (from Python program)? For example, open *.py file, find specific > >> function definition, add another function call inside, find existing > >> call and change parameter value, etc. > > You are after inspect, it is included with python. > > Yes, I forgot to mention - I'm new to Python. I didn't necessary mention > 3rd party library. Simply such wasn't mentioned in library review and > tutorials, so I didn't know of it. What's the module's name? inspect. >> What I'm trying to implement isn't a real visual programming tool, but > >> some code-generation is necessary. For now I think I can generate Python > >> syntax manually (like any text file), but it can become more complicated > >> in future (like partially implementing code-generation library), plus > >> there'll always be possibility of corrupting files and losing data (or > >> having to recover valid Python syntax manually) due to coding mistake. > > Generating code like this is always dangerous. Maybe you could > > generate some other kind of file, then use some library or build one, > > to operator over this file. > > No, the code by itself is the goal. From ianmbloom at gmail.com Mon Feb 11 18:57:00 2008 From: ianmbloom at gmail.com (ibloom) Date: Mon, 11 Feb 2008 15:57:00 -0800 (PST) Subject: Difficulty with "inconsistent use of tabs and spaces in indentation" in file called References: <3a894604-6bbb-4482-aacc-cb36bc6e5de5@s13g2000prd.googlegroups.com> Message-ID: <18224a36-a55d-41be-8209-88d06f116a1c@f10g2000hsf.googlegroups.com> My main problem is, I don't know where to find the file: File "", line 628 As in I don't know what code it is refering to by ?? It isn't code that I wrote, its something from python or pyObjC Ian Bloom From ptmcg at austin.rr.com Sun Feb 17 21:57:52 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 17 Feb 2008 18:57:52 -0800 (PST) Subject: CSV module: incorrectly parsed file. References: <4733861b-8128-4cec-9d0b-6543e923a0e3@s13g2000prd.googlegroups.com> Message-ID: <394b935c-c945-49c9-bd1f-6c5744db1a15@o10g2000hsf.googlegroups.com> On Feb 17, 8:09?pm, Christopher Barrington-Leigh wrote: > Here is a file "test.csv" > number,name,description,value > 1,"wer","tape 2"",5 > 1,vvv,"hoohaa",2 > > I want to convert it to tab-separated without those silly quotes. Note > in the second line that a field is 'tape 2"' , ie two inches: there is > a double quote in the string. > What is needed to disambiguate this data is to only accept closing quotes if they are followed by a comma or the end of the line. In pyparsing, you can define your own quoted string format. Here is one solution using pyparsing. At the end, you can extract the data by field name, and print it out however you choose: data = """\ number,name,description,value 1,"wer","tape 2"",5 1,vvv,"hoohaa",2""" from pyparsing import * # very special definition of a quoted string, that ends with a " only if # followed by a , or the end of line quotedString = ('"' + ZeroOrMore(CharsNotIn('"')|('"' + ~FollowedBy(','|lineEnd))) + '"') quotedString.setParseAction(keepOriginalText, removeQuotes) integer = Word(nums).setParseAction(lambda toks:int(toks[0])) value = integer | quotedString | Word(printables.replace(",","")) # first pass, just parse the comma-separated values for line in data.splitlines(): print delimitedList(value).parseString(line) print # now second pass, assign field names using names from first line names = data.splitlines()[0].split(',') def setValueNames(tokens): for k,v in zip(names,tokens): tokens[k] = v lineDef = delimitedList(value).setParseAction(setValueNames) # parse each line, and extract data by field name for line in data.splitlines()[1:]: results = lineDef.parseString(line) print "Desc:", results.description print results.dump() Prints: ['number', 'name', 'description', 'value'] [1, 'wer', 'tape 2"', 5] [1, 'vvv', 'hoohaa', 2] Desc: tape 2" [1, 'wer', 'tape 2"', 5] - description: tape 2" - name: wer - number: 1 - value : 5 Desc: hoohaa [1, 'vvv', 'hoohaa', 2] - description: hoohaa - name: vvv - number: 1 - value : 2 -- Paul From dickinsm at gmail.com Sun Feb 10 20:29:05 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Sun, 10 Feb 2008 17:29:05 -0800 (PST) Subject: Turn off ZeroDivisionError? References: <63d2e7d1-aa26-4ddc-9d12-42ae636104c1@s37g2000prg.googlegroups.com> <13qunlu5nrva731@corp.supernews.com> Message-ID: <91db91f2-daef-4e32-b287-b2dadb76fa0f@m34g2000hsb.googlegroups.com> On Feb 10, 7:08?pm, Carl Banks wrote: > I understand your pain, but Python, like any good general-purpose > language, is a compromise. ?For the vast majority of programming, > division by zero is a mistake and not merely a degenerate case, so > Python decided to treat it like one. Agreed. For 'normal' users, who haven't encountered the ideas of infinities and NaNs, floating-point numbers are essentially a computational model for the real numbers, and operations that are illegal in the reals (square root of -1, division by zero) should produce Python exceptions rather than send those users hurrying to comp.lang.python to complain about something called #IND appearing on their screens. But for numerically-aware users it would be nice if it were possible to do non-stop IEEE arithmetic with infinities and NaNs. Any suggestions about how to achieve the above-described state of affairs are welcome! Mark From gagsl-py2 at yahoo.com.ar Sat Feb 2 22:38:21 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 03 Feb 2008 01:38:21 -0200 Subject: Does anyone else use this little idiom? References: <8a6b8e350802021903q4cffc037s3bc29605ae3f0e9c@mail.gmail.com> Message-ID: En Sun, 03 Feb 2008 01:03:43 -0200, James Matthews escribi?: Sorry to be nitpicking, but people coming from other languages may get confused by the wrong examples: > What i do is a simple range call. for i in range(number of times i want > to repeat something) > I guess it comes from my C days for(i=0;i<100;i++) { or in python for i > in range(99): Should be `for i in range(100)` to match exactly the C loop. Both iterate 100 times, with i varying from 0 to 99 inclusive. >> miller.paul.w at gmail.com wrote: >> >> > Ruby has a neat little convenience when writing loops where you don't >> > care about the loop index: you just do n.times do { ... some >> > code ... } where n is an integer representing how many times you want >> > to execute "some code." >> > >> > In Python, the direct translation of this is a for loop. When the >> > index doesn't matter to me, I tend to write it as: >> > >> > for _ in xrange (1,n): >> > some code Should be `for _ in xrange(n)` to match the Ruby example. Both iterate n times. > On Feb 3, 2008 3:34 AM, Roy Smith wrote: > >> But, more to the point, I'd try to find variable name which described >> why I was looping, even if I didn't actually use the value in theloop >> body: Me too. Government don't collect taxes by the number of variable names used (yet). -- Gabriel Genellina From ValdezDE at googlemail.com Fri Feb 8 03:13:48 2008 From: ValdezDE at googlemail.com (ValdezDE at googlemail.com) Date: Fri, 8 Feb 2008 00:13:48 -0800 (PST) Subject: print 'hello' -> SyntaxError: invalid syntax References: <3f38aeeb-f12b-411d-ac80-1038d8c524b7@d21g2000prf.googlegroups.com> <955c0372-7f1f-43fc-a814-6feb80ef643b@m34g2000hsb.googlegroups.com> Message-ID: On Feb 7, 10:21 pm, ajaksu wrote: > On Feb 7, 12:52 pm, Valde... at googlemail.com wrote: > > > I try to install Python in a Dell D620 with XP PRO version 5.1.2600 > > and I am getting this error. I assume that some dlls are missing but I > > installed form a fresh python-2.5.1.msi without errors msg. > > > Thanks > > > Roberto > > What is the install path? And what is your locale? > > What happens if you type "Ctrl + m" instead of Return after your input? Python is installed in c:\Python25 ans "ctr + m" produce the same error msg as Return. I did a new install and the problem is still there :-( thanks Roberto From bj_666 at gmx.net Fri Feb 22 10:19:35 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 22 Feb 2008 15:19:35 GMT Subject: Acting like button are being pressed (BUT THEY ARE NOT) Please Help References: Message-ID: <6287g7F21f45aU2@mid.uni-berlin.de> On Fri, 22 Feb 2008 06:48:37 -0800, mcsejung wrote: > [snipped massive bit of code] Sorry but dumping about 900 lines of code at people with no real question in the message body and just sort of a question in the subject won't help much to get answers. Just a quick look at the code tells that it could use some loops to refactor it into a **much** shorter piece of code. Then get rid of the asterisk import, ``except``\s without a specific exception to handle, and the``global`` statement before you repost the problem. Ciao, Marc 'BlackJack' Rintsch From emailamit at gmail.com Wed Feb 6 17:07:23 2008 From: emailamit at gmail.com (Amit Gupta) Date: Wed, 6 Feb 2008 14:07:23 -0800 (PST) Subject: getting all user defined attributes of a class Message-ID: <305a63f1-70b0-4234-ac6f-4fa1a43b5c78@e10g2000prf.googlegroups.com> Hi How do I get user defined attributes of a class? e.g Class A(object) : self.x = 1 ------------------ I want something like: for userattrib in A.getAllUserAttribute() : print userattrib My question is, is there a builtin function, called getAllUserAttributes? Thanks From deets at nospam.web.de Mon Feb 11 04:40:40 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 11 Feb 2008 10:40:40 +0100 Subject: packing greyscale values References: <71215618-85cd-4ad5-9e95-354f9859fc4d@s37g2000prg.googlegroups.com> Message-ID: <61ajgoF1ug3elU1@mid.uni-berlin.de> jimgardener wrote: > hi > i am getting value of a pixel of a greyscale image using PIL's > image.getdata and need to pack it as an int as below > > ie greyvalues > 127 , 56 , 135 , 99 , 102 , 101 , 146 , 112 , 155 , 154 , 112 , 169 > > should become > -4473925, -8289919, -4144960, -5789785, -5592406, -5658199 ,-3684409, > -5131855, -3289651,-3355444, -5131855, -2763307 > > (i got these values using java's BufferedImage class..)I would like to > know if there is a way to do the conversion in python.(.i need 'these > 'for some calculations) I have no idea how the bytes from PIL are possibly mapped to the wicked numbers Java seems to generate (although there might be some systematics to it). But judging from the fact that 112->-5131855 appears twice, I presume as last resort you could create an explicit mapping of 0..255 to the values Java generates. To get these, create an image, 256 pixels wide, one high, with grey-values from #000000 to #ffffff. Then build up the mapping. Not elegant, but works. Diez From Robert.Bossy at jouy.inra.fr Wed Feb 20 03:29:12 2008 From: Robert.Bossy at jouy.inra.fr (Robert Bossy) Date: Wed, 20 Feb 2008 09:29:12 +0100 Subject: distutils and data files In-Reply-To: <87odacmnc4.fsf@nospam.please.ucdavis.edu> References: <87odacmnc4.fsf@nospam.please.ucdavis.edu> Message-ID: <47BBE4D8.6000908@jouy.inra.fr> Sam Peterson wrote: > I've been googling for a while now and cannot find a good way to deal > with this. > > I have a slightly messy python program I wrote that I've historically > just run from the extracted source folder. I have pictures and sound > files in this folder that this program uses. I've always just used > the relative path names of these files in my program. > > Lately, I had the idea of cleaning up my program and packaging it with > distutils, but I've been stuck on a good way to deal with these > resource files. The package_data keyword seems to be the way to go, > but how can I locate and open my files once they've been moved? In > other words, what should I do about changing the relative path names? > I need something that could work from both the extracted source > folder, AND when the program gets installed via the python setup.py > install command. > This seems to be a classic distutils question: how a python module can access to data files *after* being installed? The following thread addresses this issue: http://www.gossamer-threads.com/lists/python/python/163159 Carl Banks' solution seems to overcome the problem: his trick is to generate an additional configuration module with the relevant informations from the distutil data structure. However it is quite an old thread (2003) and I don't know if there has been progress made since then, maybe the distutils module now incorporates a similar mechanism. Hope it helps, RB From google at mrabarnett.plus.com Tue Feb 5 20:22:11 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 5 Feb 2008 17:22:11 -0800 (PST) Subject: Using Regular Expressions to Parse SQL References: Message-ID: On Feb 5, 6:18 pm, c... at aol.com wrote: > Firstly, thanks to those who posted. > > I just do not understand how the non-greedy operator works. > > Using the following code: > > import re > > s = "qry_Lookup.desc = CSS_Rpt1.desc AND qry_Lookup.lcdu1 = > CSS_Rpt1.lcdu" > > pat = "(.+=)+?(.+)" ^^ | This is your problem. The ".+" is greedy and is matching up to the last "=". Try "(.+?=)(. +)" instead. > > m = re.match(pat, s) > > if m is None: > print "No Match" > else: > for mat in m.groups(): > print mat > > I would expect that the first group would match one or more times with > the fewest amount of text. However the result is: > > >qry_Lookup.desc = CSS_Rpt1.desc AND qry_Lookup.lcdu1 = > > CSS_Rpt1.lcdu > > The first match of the "=" char is still greedy. I would have > expected: > qry_Lookup.desc = > > > CSS_Rpt1.desc AND qry_Lookup.lcdu1 > > = > > CSS_Rpt1.lcdu > > I'm obviously missing something because the non-greedy match seems to > not be acting as expected. > > Any insights would be greatly appreciated. > > Thanks in advance, > > Chris (c... at aol.com) > > On Feb 5, 9:31 am, c... at aol.com wrote: > > > Hello again - > > > I do not seem to be able to get a handle on non-greedy pattern > > matching. > > > I am trying to parse the following - note that there are no line > > breaks in the string: > > > " FROM ((qry_Scores_Lookup1 INNER JOIN CSS_Rpt1 ON > > (qry_Scores_Lookup1.desc = CSS_Rpt1.desc) AND > > (qry_Scores_Lookup1.lastcdu = CSS_Rpt1.lastcdu))" > > > What I would like to do is be able to split on the "AND" and the "=" > > to come up with the following: > > qry_Scores_Lookup1.desc > > CSS_Rpt1.desc > > qry_Scores_Lookup1.lastcdu > > CSS_Rpt1.lastcdu > > > The following is one of my many attempts to do this: > > > import re > > > s= " FROM ((qry_Scores_Lookup1 INNER JOIN CSS_Rpt1 ON > > (qry_Scores_Lookup1.desc = CSS_Rpt1.desc) AND > > (qry_Scores_Lookup1.lastcdu = CSS_Rpt1.lastcdu))" > > > pat = " FROM .+ (?:INNER|LEFT|RIGHT) JOIN .+ ON (?:AND)*?((.+)=(.+))" > > > m = re.match(pat, s) > > > if m is None: > > print "No Match" > > else: > > for mat in m.groups(): > > print mat > > > My pattern does not even come close. > > > Any help would be greatly appreciated. My goal is to analyse a large > > number of SQL querys to try to identify the join field and see where > > indexing might make sense. > > > While I am mostly interested in understanding regular expressions, I > > would also be interested in knowing about any Python SQL parsers out > > there. > > > Thanks in advance. > > > Chris (c... at aol.com) From nytrokiss at gmail.com Sun Feb 10 15:57:32 2008 From: nytrokiss at gmail.com (James Matthews) Date: Sun, 10 Feb 2008 21:57:32 +0100 Subject: Displaying Unicode Chars In-Reply-To: <3c525772-85b1-49ff-a46b-48e7f03df6ca@v4g2000hsf.googlegroups.com> References: <3c525772-85b1-49ff-a46b-48e7f03df6ca@v4g2000hsf.googlegroups.com> Message-ID: <8a6b8e350802101257l6ab23fbyebf2bcf8f5b1569@mail.gmail.com> Why don't you use ord? 2008/2/10 gregpinero at gmail.com : > I want to make a little Python utility where a user can enter the > unicode numerical code and get the actual symbol back in utf-8. > > For example, a user could enter something like u221E > > And get back ? > > Now, this does seem to work: > > >>> print u"\u221E" > ? > However how can I change it so it works with a string variable? > > print unicode("\u221E") doesn't seem to do it. > > I hope this makes sense. I don't know all the unicode terminology to > phrase this question coherently ;-) > > Thanks in advance, > > Greg > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://search.goldwatches.com/?Search=Movado+Watches http://www.jewelerslounge.com http://www.goldwatches.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Fri Feb 29 09:30:28 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 29 Feb 2008 09:30:28 -0500 Subject: You have to see this - http://ilaarijs.blogspot.com/ :D In-Reply-To: <29224030-1f00-4330-bf9e-9a50fe9f9049@d21g2000prf.googlegroups.com> References: <29224030-1f00-4330-bf9e-9a50fe9f9049@d21g2000prf.googlegroups.com> Message-ID: plikadirsa at gmail.com wrote: > You have to see this - http://... :D Sorry. I don't. -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From arnodel at googlemail.com Fri Feb 1 02:13:37 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 31 Jan 2008 23:13:37 -0800 (PST) Subject: dict comprehension References: Message-ID: <22563849-ba45-4dfa-9782-78ef637be30f@s8g2000prg.googlegroups.com> On Feb 1, 6:21?am, "Terry Reedy" wrote: > "Daniel Fetchinson" wrote in message > > news:fbe2e2100801312151x7136d1bbu3498d7d21728100e at mail.gmail.com... > | Hi folks, > | > | There is a withdrawn PEP about a new syntax for dict comprehension: > |http://www.python.org/dev/peps/pep-0274/which says: > > I believe both set and dict comprehensions will be in 3.0. Python 3.0a1+ (py3k:59330, Dec 4 2007, 18:44:39) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> {x*x for x in range(10)} {0, 1, 4, 81, 64, 9, 16, 49, 25, 36} >>> {x:x*x for x in range(10)} {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81} >>> That's nice. -- Arnaud From gagsl-py2 at yahoo.com.ar Wed Feb 6 02:18:39 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 06 Feb 2008 05:18:39 -0200 Subject: Using a class as a structure/container References: <31f9058a-60a9-47b5-9c05-bddb31d2d04c@u10g2000prn.googlegroups.com> Message-ID: En Wed, 06 Feb 2008 00:59:48 -0200, escribi?: > Is it appropriate to use a class as a simple container in order to > access attributes using a series of dot operators? Is their a more > Pythonic way of doing this? For instance, I have a "container" class > which is never instantiated directly, but only through another class. > Access to certain attributes would be something like: > > main_class.a.b.x > > where row and v1 are instances of the container class which are > instantianted by main_class. I know I can use dictionaries, but this > syntax is a little clearer as long as the number of dot operators is > not too lengthy. Some code would be something like: > > class container(object): > def __init__(self): > pass You can omit the __init__ method if it's empty > class main_class(object): > def __init__(self): > self.a = container() > settatr(self.a, 'b', container()) > settatr(self.a.b, 'x', 2) Usually written as: self.a.b = container() self.a.b.x = 2 Nothing in the language forbids doing what you do, but I'd ask if the attributes may be split logically between the various containers, or it is an artificial division and they really should be attributes of the main_class. There are documentation problems too: such generic container cannot tell which attributes are valid or not; introspection tools cannot tell very much about the class; perhaps some code completion tools get confused. I don't like a long sequence of dots either. Using such a deep structure you are violating the Law of Demeter "Don't talk to strangers" http://en.wikipedia.org/wiki/Law_of_Demeter (altough I don't follow it strictly, things like xobj.parent.connection.user.name look wrong to me) Another problem of such generic container is that you don't get any meaningful information when printing it. You may find the NamedTuples recipe useful; look into the Python Cookbook http://www.activestate.com/ASPN/Python/Cookbook/ - or perhaps using this class: class Record(object): def __init__(self, **kw): self.__dict__.update(kw) def __repr__(self): values = ['%s=%r' % item for item in sorted(self.__dict__.iteritems())] return '%s(%s)' % (self.__class__.__name__, ','.join(values)) __str__ = __repr__ x = Record(a=1, b=2.0, c="three") print x # output: Record(a=1,b=2.0,c='three') -- Gabriel Genellina From bignose+hates-spam at benfinney.id.au Wed Feb 6 20:33:46 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 07 Feb 2008 12:33:46 +1100 Subject: loading dictionary from a file References: <58aa1a6b-4960-4b03-85fa-da9c9c630ccc@n20g2000hsh.googlegroups.com> Message-ID: <87wspha6th.fsf@benfinney.id.au> Amit Gupta writes: > Need a python trick, if it exists: > > I have a file that stores key, value in following format > -- > "v1" : "k1", > "v2" : "k2" > -- > > Is there a way to directly load this file as dictionary in python. That input looks almost like valid JSON . If you can easily massage it into JSON format, you can use the Python JSON library : import json input_text = open('foo.txt').read() input_json = "{%(input_text)s}" % vars() reader = json.JsonReader() data = reader.read(input_json) If the 'input_json' above actually is valid JSON, that will give the corresponding Python data object. This avoids the massive security hole of performing 'eval' on arbitrary user input; the input isn't executed, merely parsed (as JSON) to create a data object. -- \ ?I busted a mirror and got seven years bad luck, but my lawyer | `\ thinks he can get me five.? ?Steven Wright | _o__) | Ben Finney From MartinRinehart at gmail.com Sun Feb 17 14:38:04 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Sun, 17 Feb 2008 11:38:04 -0800 (PST) Subject: Linux/Python Issues Message-ID: I went to Python.org, DL'd Python 2.5 source code per the usual inadequate instructions and ran the make files successfully (sort of). Python 2.5 works fine. But "from Tkinter import *" gets a "What's Tkinter?" message. IDLE's no where to be found. What's not in the instructions is what directory should I be in when I download? Where should I put the ".bz2" file? What dir for running the make files? At present I'm working on a Windows machine, endangering what's left of my sanity. I'm using Linspire, so Debian directories are probably the ones that will get me up and running. Barring specific knowledge, even some good guesses would be appreciated. From hyugaricdeau at gmail.com Fri Feb 8 09:34:10 2008 From: hyugaricdeau at gmail.com (Hyuga) Date: Fri, 8 Feb 2008 06:34:10 -0800 (PST) Subject: re question References: <8d6f4d80-d979-4baf-925e-b6cd1daed79d@s19g2000prg.googlegroups.com> Message-ID: <71d3bfba-0e46-4b8b-b7f4-e5c04d3eda69@s8g2000prg.googlegroups.com> On Feb 7, 1:47 pm, Amit Gupta wrote: > On Feb 7, 10:38 am, Amit Gupta wrote: > > > > > Python'ites > > > I searched around "google" to find the answer to this question, but I > > can't: > > > I have a named regexp : x = re.compile("(?P[a-z]+)") > > > What I want is an iterator, that can return me both the "groupname" > > and the matched string, e.g: > > > m = x.search("aa") > > > Somehow, I want to get > > {"me" : "aa"}, either as dictionary or some iterable form. > > > All I found is, I need to know the "groupname" to get the > > corresponding match. Any help is appreciated. > > > A > > Got It. re.search() has a function groupdict(), doing precisely that. Just to be pedantic so that no one else who might read this does not get confused, re.search() does not "[have] a function groupdict()". re.search(), like many function in the re module returns a match object. Match objects have a groupdict() method. Hyuga From bkasterm at gmail.com Sat Feb 2 22:32:49 2008 From: bkasterm at gmail.com (Bart Kastermans) Date: Sat, 2 Feb 2008 19:32:49 -0800 (PST) Subject: Gmail imap search does not get all messages. References: <60cd1edc-761c-4e68-b110-65df54f3c6b3@l32g2000hse.googlegroups.com> Message-ID: Quick update on the below: the issue has disappeared by itself. I did not get to working on this much since sending my last message. Now that I am looking at this the issue has disappeared. On Jan 29, 8:23?pm, Bart Kastermans wrote: > I am trying to use imaplib with gmail. ?I am finding however that with > the gmail server imaplib.search does not give the correct answer. ?See > the below traces (k is a server a my department, i is gmail). > k has 6 messages in the INBOX > i has 3 messages in the INBOX > > However i.search(None, "ALL") > only gives as answer "1 2", missing the third message. > > Any suggestions about what I might be doing wrong? ?Or is this a known > issue? ?I couldn't find anything by googling, but maybe I am using the > wrong search terms. > > Best, > Bart > > >>> k.select() > > ? 05:41.11 > FEIC2 SELECT INBOX > ? 05:41.16 < * FLAGS (\Answered \Flagged \Deleted \Seen \Draft MATH > $Forwarded $label5 $label1 $label4 $label2 $label3 NonJunk $NotJunk > $Junk JunkRecorded) > ? 05:41.16 < * OK [PERMANENTFLAGS (\Answered \Flagged \Deleted \Seen > \Draft MATH $Forwarded $label5 $label1 $label4 $label2 $label3 NonJunk > $NotJunk $Junk JunkRecorded \*)] Flags permitted. > ? 05:41.16 < * 6 EXISTS > ? 05:41.16 < * 0 RECENT > ? 05:41.16 < * OK [UIDVALIDITY xXxXxXxXxX] UIDs valid > ? 05:41.16 < * OK [UIDNEXT xXxXxXxX] Predicted next UID > ? 05:41.16 < FEIC2 OK [READ-WRITE] Select completed. > ('OK', ['6'])>>> k.search(None,"ALL") > > ? 05:52.82 > FEIC3 SEARCH ALL > ? 05:52.86 < * SEARCH 1 2 3 4 5 6 > ? 05:52.86 < FEIC3 OK Search completed. > ('OK', ['1 2 3 4 5 6']) > > >>> i.select() > > ? 10:23.16 > DKNG10 SELECT INBOX > ? 10:23.30 < * FLAGS (\Answered \Flagged \Draft \Deleted \Seen) > ? 10:23.30 < * OK [PERMANENTFLAGS (\Answered \Flagged \Draft \Deleted > \Seen \*)] > ? 10:23.30 < * OK [UIDVALIDITY xXxXxXxXx] > ? 10:23.30 < * 3 EXISTS > ? 10:23.30 < * 0 RECENT > ? 10:23.30 < * OK [UNSEEN 3] > ? 10:23.30 < * OK [UIDNEXT 7] > ? 10:23.31 < DKNG10 OK [READ-WRITE] INBOX selected. (Success) > ('OK', ['3'])>>> i.search(None,"ALL") > > ? 10:17.30 > DKNG9 SEARCH ALL > ? 10:17.44 < * SEARCH 1 2 > ? 10:17.44 < DKNG9 OK SEARCH completed (Success) > ('OK', ['1 2']) From martin at v.loewis.de Sat Feb 2 15:28:09 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 02 Feb 2008 21:28:09 +0100 Subject: What should I use under *nix instead of freeze? In-Reply-To: <47a4678b$0$5953$9b4e6d93@newsspool3.arcor-online.net> References: <7498f946-9ea6-48fe-a509-c80cf425af11@j78g2000hsd.googlegroups.com> <47A3C77F.60801@v.loewis.de> <47a4678b$0$5953$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <47A4D259.4020700@v.loewis.de> >>> That being the case, what is the preferred/best replacement for freeze >>> on a *nix platform? >> >> I don't think that there is one, or that there should be one. >> > > So haven't I understood what freeze does? Isn't pyinstaller just that? No. First, it works on Windows, Linux and Irix only, not on arbitrary *nix systems. Second, it doesn't create a single executable, but depends on the extension modules that the host Python interpreter uses. To compile a simple "print 'Hello, world'" with Python 2.5 on Debian, I get an executable consisting of 22 binaries. Regards, Martin From arnodel at googlemail.com Mon Feb 25 18:42:37 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 25 Feb 2008 15:42:37 -0800 (PST) Subject: Python code for 2.5 and 2.4? References: <28a84535-483d-461d-828d-bb9a38be19f0@v3g2000hsc.googlegroups.com> <90aa62f8-ae45-485f-b847-106bb8950a88@71g2000hse.googlegroups.com> <7xpruktylj.fsf@ruckus.brouhaha.com> Message-ID: <2912ad02-085e-4b0e-a63d-7b10155b376b@d4g2000prg.googlegroups.com> On Feb 25, 11:17?pm, Paul Rubin wrote: > Arnaud Delobelle writes: > > ? ? def all(iterable): > > ? ? ? ? for x in iterable: > > ? ? ? ? ? ? if not x: return False > > ? ? ? ? return True > > from itertools import imap > def all(iterable): > ? ?return False not in imap(bool, iterable) Ok. In that case, the following is probably faster (in fact for long iterables it may be equivalent to the builtin all): from itertools import ifilterfalse def all(iterable): for _ in ifilterfalse(None, iterable): return False return True But my point was really about not checking for the version but just checking for the existence of the name 'all'. -- Arnaud From ebgssth at gmail.com Sun Feb 24 00:16:18 2008 From: ebgssth at gmail.com (js) Date: Sun, 24 Feb 2008 14:16:18 +0900 Subject: Official IRC channel for Python? In-Reply-To: <7xskzj7yw9.fsf@ruckus.brouhaha.com> References: <7xskzj7yw9.fsf@ruckus.brouhaha.com> Message-ID: Really? maybe I'm been blocked from it... thanks. On 23 Feb 2008 20:37:42 -0800, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > js writes: > > I tried #python irc.freenode.net > > That has always worked for me. > > -- > http://mail.python.org/mailman/listinfo/python-list > From steve at holdenweb.com Tue Feb 19 07:19:33 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 19 Feb 2008 07:19:33 -0500 Subject: ANN: Phatch = PHoto bATCH processor and renamer based on PIL In-Reply-To: <15f9eaeb-8d02-4090-922e-97a65c20fe51@e23g2000prf.googlegroups.com> References: <15f9eaeb-8d02-4090-922e-97a65c20fe51@e23g2000prf.googlegroups.com> Message-ID: <47BAC955.60702@holdenweb.com> SPE - Stani's Python Editor wrote: > I'm pleased to announce the release of Phatch which is a > powerful batch processor and renamer. Phatch exposes a big part of the > Python Imaging Library through an user friendly GUI. (It is using > python-pyexiv2 to offer more extensive EXIF and IPTC support.) Phatch > is not targeted at manipulating individual pictures (such as with > Gimp), but repeating the same actions on hundreds or thousands of > images. > Perhaps you could put a link to the source on the Windows instalL page? I don't mind being a second-class citizen, but it's annoying to have to jump around like that. Looks like a nice piece of work. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From Lie.1296 at gmail.com Tue Feb 26 06:54:49 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 26 Feb 2008 03:54:49 -0800 (PST) Subject: How about adding rational fraction to Python? References: <70ecaf16-7308-455f-9048-730b2b2f9f2f@p43g2000hsc.googlegroups.com> <13rf9tvbkt66r2a@corp.supernews.com> <198927a7-9478-42b3-a972-82049f0130ac@u10g2000prn.googlegroups.com> <1bc9bba7-dc7f-4cfe-8e1c-fa5901c9f556@n77g2000hse.googlegroups.com> <97f30679-483d-4751-9a6e-0858b36eb426@d4g2000prg.googlegroups.com> <649ac8a9-ae09-4e9b-85c2-f37043af21fd@28g2000hsw.googlegroups.com> <13s3smnkp06arcd@corp.supernews.com> Message-ID: <3b9f5be6-6e43-478c-9d4c-cba3101234d3@64g2000hsw.googlegroups.com> On Feb 25, 5:41 am, Steven D'Aprano wrote: > On Sun, 24 Feb 2008 10:09:37 -0800, Lie wrote: > > On Feb 25, 12:46 am, Steve Holden wrote: > >> Lie wrote: > >> > On Feb 18, 1:25 pm, Carl Banks wrote: > >> >> On Feb 17, 1:45 pm, Lie wrote: > > >> >>>> Any iteration with repeated divisions and additions can thus run > >> >>>> the denominators up. This sort of calculation is pretty common > >> >>>> (examples: compound interest, numerical integration). > >> >>> Wrong. Addition and subtraction would only grow the denominator up > >> >>> to a certain limit > >> >> I said repeated additions and divisions. > > >> > Repeated Addition and subtraction can't make fractions grow > >> > infinitely, only multiplication and division could. > > >> On what basis is this claim made? > > >> (n1/d1) + (n2/d2) = ((n1*d2) + (n2*d1)) / (d1*d2) > > >> If d1 and d2 are mutually prime (have no common factors) then it is > >> impossible to reduce the resulting fraction further in the general case > >> (where n1 = n2 = 1, for example). > > >> >> Anyways, addition and subtraction can increase the denominator a lot > >> >> if for some reason you are inputing numbers with many different > >> >> denominators. > > >> > Up to a certain limit. After you reached the limit, the fraction > >> > would always be simplifyable. > > >> Where does this magical "limit" appear from? > > >> > If the input numerator and denominator have a defined limit, repeated > >> > addition and subtraction to another fraction will also have a defined > >> > limit. > > >> Well I suppose is you limit the input denominators to n then you have a > >> guarantee that the output denominators won't exceed n!, but that seems > >> like a pretty poor guarantee to me. > > >> Am I wrong here? You seem to be putting out unsupportable assertions. > >> Please justify them or stop making them. > > > Well, I do a test on my own fraction class. I found out that if we set a > > limit to the numerators and denominators, the resulting output fraction > > would have limit too. I can't grow my fraction any more than this limit > > no matter how many iteration I do on them. I do the test is by something > > like this (I don't have the source code with me right now, it's quite > > long if it includes the fraction class, but I think you could use any > > fraction class that automatically simplify itself, might post the real > > code some time later): > > > while True: > > a = randomly do (a + b) or (a - b) > > b = random fraction between [0-100]/[0-100] print a > > > And this limit is much lower than n!. I think it's sum(primes(n)), but > > I've got no proof for this one yet. > > *jaw drops* > > Please stop trying to "help" convince people that rational classes are > safe to use. That's the sort of "help" that we don't need. > > For the record, it is a perfectly good strategy to *artificially* limit > the denominator of fractions to some maximum value. (That's more or less > the equivalent of setting your floating point values to a maximum number > of decimal places.) But without that artificial limit, repeated addition > of fractions risks having the denominator increase without limit. > > -- > Steven No, it is a real limit. This is what I'm talking about. If the input data has a limit, the output data has a real limit, not a user-defined- limit (FOR ADDITION AND SUBTRACTION). If the input data's denominator is unbounded, the output fraction's denominator is also unbounded From brainbeez at gmail.com Tue Feb 12 08:01:59 2008 From: brainbeez at gmail.com (Ria) Date: Tue, 12 Feb 2008 05:01:59 -0800 (PST) Subject: Free Certifications from www.Brainbeez.com Message-ID: <40113f07-d18f-4b44-a2f7-25e3c4ff3e52@s13g2000prd.googlegroups.com> Hi, www.brainbeez.com is offering free certifications on various IT and NON-IT subjects like Aptitude, English, C, C++, JAVA, ORACLE, FINANCE, MARKETING ETC., Do visit www.brainbeez.com and get certified for free instantly. Certificate is directly send to your email account once you qualify the exam. Thanks, Ria ! From jeff at schwabcenter.com Wed Feb 27 22:12:00 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Wed, 27 Feb 2008 19:12:00 -0800 Subject: Article of interest: Python pros/cons for the enterprise In-Reply-To: References: <3b3111d3-699d-4f8d-b99e-87a0666f60a7@b29g2000hsa.googlegroups.com> Message-ID: Aahz wrote: > In article <3b3111d3-699d-4f8d-b99e-87a0666f60a7 at b29g2000hsa.googlegroups.com>, > Carl Banks wrote: >> On Feb 24, 7:03 pm, a... at pythoncraft.com (Aahz) wrote: >>> In article , >>> Jeff Schwab wrote: >>>> (3) Garbage collection is at least as desirable a language feature as >>>> deterministic destruction. >>> Enh. There probably are some people who claim that, but I can't think >>> of any off-hand. >> I am most certainly claiming it; in fact I'm claiming that GC far more >> desirable, because the cost of deterministic destruction is too high. > > I'm trimming the rest of your post because I don't have time to argue > with you, but I want to point out that you're making the same mistake > that Jeff is: garbage collection and deterministic destruction are not > the only techniques for managing memory and resources. In particular, > CPython primarily relies on reference counting That is GC. It's just not mark & sweep. >, which has similarities > with *both* GC and deterministic destruction. > > Now you know why I said that I don't know anybody who makes Jeff's > claim. ;-) From TimeHorse at gmail.com Mon Feb 25 07:50:06 2008 From: TimeHorse at gmail.com (TimeHorse) Date: Mon, 25 Feb 2008 04:50:06 -0800 (PST) Subject: Adding Priority Scheduling feature to the subprocess References: <5db9ca17-c877-4b5b-b430-41519faa43f0@z70g2000hsb.googlegroups.com> <13rrg14apf2mcb9@corp.supernews.com> <1cf2c0a5-a444-4967-9d90-35316751808d@o77g2000hsf.googlegroups.com> Message-ID: <462db00b-6377-4354-8da4-bdd6a3494925@k2g2000hse.googlegroups.com> On Feb 22, 4:30?am, Nick Craig-Wood wrote: > Interestingly enough this was changed in recent linux kernels. > Process levels in linus kernels are logarithmic now, whereas before > they weren't (but I wouldn't like to say exactly what!). Wow! That's a VERY good point. I ran a similar test on Windows with the 'start' command which is similar to nice but you need to specify the Priority Class by name, e.g. start /REALTIME python.exe bench1.py Now, in a standard operating system you'd expect some variance between runs, and I did find that. So I wrote a script to compute the Mode (but not the Standard Deviation as I didn't have time for it) for each Priority Class, chosen each run at random, accumulated the running value for each one. Now, when I read the results, I really wish I'd computed the Chi**2 to calculate the Standard Deviation because the results all appeared within very close relation to one another, as if the Priority Class had overall very little effect. In fact, I would be willing to guess that say NORMAL and ABOVENORMAL lie with one Standard Deviation of one another! That having been said, the tests all ran in about 10 seconds so it may be that the process was too simple to show any statistical results. I know for instance that running ffmpeg as NORMAL or REALTIME makes a sizable difference. So, I concede the "Unified Priority" may indeed be dead in the water, but I am thinking of giving it once last go with the following suggestion: 0.0 == Zero-Page (Windows, e.g. 0) / +20 (Unix) 1.0 == Normal (Foreground) Priority (Windows, e.g. 9) / 0 (Unix) MAX_PRIORITY == Realtime / Time Critical (Windows, e.g. 31) / -20 (Unix) With the value of MAX_PRIORITY TBD. Now, 0.0 would still represent (relatively) 0% CPU usage, but now 1.0 would represent 100% of 'Normal' priority. I would still map 0.0 - 1.0 linearly over the scale corresponding to the given operating system (0 - 9, Window; +20 - 0, Unix), but higher priorities would correspond to > 1.0 values. The idea here is that most user will only want to lower priority, not raise it, so it makes lowering pretty intuitive. As for the linear mapping, I would leave a note in the documentation that although the scale is "linear", the operating system may choose to behave as if the scale is linear and that the user should consult the documentation for their OS to determine specific behavior. This is similar to the documentation of the file time-stamps in os.stat, since their granularity differs based on OS. Most users, I should think, would just want to make their spawn "slower" and use the scale do determine "how much" in a relative fashion rather than expecting hard-and-fast numbers for the actually process retardation. Higher than Normal priorities may OTHO, be a bit harder to deal with. It strikes me that maybe the best approach is to make MAX_PRIORITY operating system dependent, specifically 31 - 9 + 1.0 = +23.0 for Windows and -20 - 0 + 1.0 = +21.0 for Unix. This way, again the priorities map linearly and in this case 1:1. I think for most users, they would choose a "High Priority" relative to MAX_PRIORITY or just choose a small increment about 1.0 to add just a little boost. Of course, the 2 biggest problems with this approach are, IMHO, a) the < Normal scale is percent but the > Normal scale is additive. However, there is no "Simple" definition of MAX_PRIORITY, so I think using the OS's definition is natural. b) This use of the priority scale may be confusing to Unix users, since 1.0 now represents "Normal" and +21, not +/-20 represents Max Priority. However, the definition of MAX_PRIORITY would be irrelevant to the definition of setPriority and getPriority, since each would, in my proposal, compute for p > 1.0: Windows: 9 + int((p - 1) / (MAX_PRIORITY - 1) * 22 + .5) Unix: -int((p - 1) / (MAX_PRIORITY - 1) * 20 + .5) Anyway, that's how I'd propose to do the nitty-gritty. But, more than anything, I think the subprocess 'priority' methods should use a priority scheme that is easy to explain. And by that, I propose: 1.0 represents normal priority, 100%. Any priority less than 1 represents a below normal priority, down to 0.0, the lowest possible priority or 0%. Any priority above 1.0 represents an above normal priority, with MAX_PRIORITY being the highest priority level available for a given os. Granted, it's not much simpler than 0 is normal, -20 is highest and +20 is lowest, except in so far as it being non-intuitive to consider a lower priority number representing a higher priority. Certainly, we could conform all systems to the +20.0 to -20.0 floating point system, but I prefer not to bias the methods and honestly feel percentage is more intuitive. So, how does that sound to people? Is that more palatable? Thanks again for all the input! Jeffrey. From john106henry at hotmail.com Sat Feb 23 13:13:05 2008 From: john106henry at hotmail.com (John Henry) Date: Sat, 23 Feb 2008 10:13:05 -0800 (PST) Subject: Return value of an assignment statement? References: <67ff8198-1d7d-4690-a9b6-42ebab2e642f@p73g2000hsd.googlegroups.com> <5MSdnceVGdH0iCPanZ2dnUVZ_vPinZ2d@comcast.com> <105cfd9f-0c50-4589-8bf6-9e16227dce75@s19g2000prg.googlegroups.com> <13rvb8a820i8q1b@corp.supernews.com> <0I6dnTZWqYTkYSLanZ2dnUVZ_hWdnZ2d@comcast.com> Message-ID: <2d7e5378-38fa-4e7e-8383-1e30fd4f6975@e10g2000prf.googlegroups.com> On Feb 23, 2:59 am, Jeff Schwab wrote: > Dennis Lee Bieber wrote: > > On Fri, 22 Feb 2008 11:23:27 -0800, Jeff Schwab > > declaimed the following in comp.lang.python: > > >> I'm about through with this discussion, but FWIW, this is a real gotcha > >> for me and many others. This is a case where Python does not do what > >> many programmers expect, and it at least takes some getting used-to. > > > As opposed to the twice monthly shocked newbie discovering that a > > mutable as a function default doesn't reset on the next invocation? > > > In that aspect, it all comes down to the difference between mutables > > and immutables in Python. > > You know what's illuminating the discussion? Everybody thinks they > understand this issue, but the explanations are contradictory. It seems > like half the folks think this is an issue of mutability vs. > immutability, and the other half believe that has nothing to do with it. You mean like this: :=) def invoke_some_fct(parent): y = parent.x try: y += [ 'world' ] except: y += ( 'world', ) print y, parent.x class abc: def __init__(self): self.x=[ 'hello' ] invoke_some_fct(self) print self.x self.x=( 'hello', ) invoke_some_fct(self) print self.x hw = abc() From waltbrad at hotmail.com Sat Feb 9 00:35:14 2008 From: waltbrad at hotmail.com (waltbrad) Date: Fri, 8 Feb 2008 21:35:14 -0800 (PST) Subject: shelve.open call gives error References: Message-ID: <7c0573f4-e09c-4cb2-93a1-c44ec26cf73c@h11g2000prf.googlegroups.com> On Feb 8, 5:29 pm, "Gabriel Genellina" wrote: > En Fri, 08 Feb 2008 06:36:53 -0200, waltbrad > escribi?: > > > > > Working through the Mark Lutz book Programming Python 3rd Edition. > > > A couple of modules in the "Preview" chapter give me errors. Both on a > > shelve.open call: > > > Pretty simple code, (2nd example): > > =====code begin===== > > import shelve > > from people import Person, Manager > > > bob = Person('Bob Smith', 42, 30000, 'sweng') > > sue = Person('Sue Jones', 45, 40000, 'music') > > tom = Manager('Tom Doe', 50, 50000) > > > db = shelve.open('class-shelve') > > db['bob'] = bob > > db['sue'] = sue > > db['tom'] = tom > > db.close() > > ====code end==== > > shelve uses the anydbm module; anydbm tries to select the best database > module available, but apparently fails in your system. If you are just > learning Python, I don't think it's worth trying to fix it; instead, let's > force anydbm to use the fallback module dumbdbm (implemented in pure > python, slow, but bullet-proof, or at least arrow-proof :) ) > > Add these two lines at the start of your script: > > import dumbdbm, anydbm > anydbm._defaultmod = dumbdbm > > Remove the class-shelve.* files, if any, before running it. > > -- > Gabriel Genellina Thanks to all for the help, but the only advice that worked was Gabriel's. I actually tried to look into the issue of fixing it, but I'm just too much of a novice. I put the two lines in a seperate module that I import to save typing. But as I gain experience I'd like to return to this issue and try to fix it. Can you give me advice on how to go about that? I'm working on a win98 system. I have python on a linux system, (Kubuntu) and winxp but it's more convenient right now for me to use the 98 laptop. From castironpi at gmail.com Thu Feb 28 14:51:41 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 28 Feb 2008 11:51:41 -0800 (PST) Subject: call by reference howto???? References: <47c5f9b8$0$21935$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <492dbd31-6f65-4f36-b7af-acf42cf39d7d@34g2000hsz.googlegroups.com> On Feb 27, 6:02?pm, Tamer Higazi wrote: > Hi! > Can somebody of you make me a sample how to define a function based on > "call by reference" ??? > > I am a python newbie and I am not getting smart how to define functions, > that should modify the variable I passed by reference. > > thanks in advance > > Tamer If it's a mutable object, avoid the pitfalls of rebinding the parameter, and just modify the object. BAD: def f( a ): a= { 'this': 'that' } GOOD: def f( a ): a.clear() a[ 'this' ]= 'that' From robin at NOSPAMreportlab.com Thu Feb 14 17:39:19 2008 From: robin at NOSPAMreportlab.com (Robin Becker) Date: Thu, 14 Feb 2008 22:39:19 +0000 Subject: InstanceType tests in Python-3.0 In-Reply-To: <13r9fktdj4vara6@corp.supernews.com> References: <13r8ok4l36kr6af@corp.supernews.com> <13r9fktdj4vara6@corp.supernews.com> Message-ID: <47B4C317.903@jessikat.plus.net> Steven D'Aprano wrote: > On Thu, 14 Feb 2008 17:21:20 +0000, Robin Becker wrote: > >........ > > The way I see it, your code don't really care about the distinction > between "user-generated classes" and "built-in types", it cares about the > distinction between "classes I know about" and "other classes". > > In fact, your existing code doesn't even catch all examples of user- > generated classes. It (or at least the snippet you have posted) has no > branch catching new-style classes. > ...... in fact there are no old style classes in 3.0 any more. There appears to be a distinction between types and classes, but I'm not going to rely on that. Have to recode all of that polymorphic stuff :( -- Robin Becker From ggpolo at gmail.com Sat Feb 9 09:22:01 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Sat, 9 Feb 2008 12:22:01 -0200 Subject: Edit Python code programmatically In-Reply-To: <47ADAEA2.6090702@gmail.com> References: <47AD90B5.9030504@gmail.com> <47AD983B.8050908@gmail.com> <47ADAEA2.6090702@gmail.com> Message-ID: 2008/2/9, Alex : > Guilherme Polo wrote: > > 2008/2/9, Arnaud Delobelle : > > > >> On Feb 9, 12:32 pm, "Guilherme Polo" wrote: > >> > 2008/2/9, Alex : > >> > > >> > > Guilherme Polo wrote: > >> > > > 2008/2/9, Alex : > >> > >> > >> > > >> Which library could you recommend to perform simple editing of Python > >> > > >> code (from Python program)? For example, open *.py file, find specific > >> > > >> function definition, add another function call inside, find existing > >> > > >> call and change parameter value, etc. > >> > > > You are after inspect, it is included with python. > >> > > >> > > Yes, I forgot to mention - I'm new to Python. I didn't necessary mention > >> > > 3rd party library. Simply such wasn't mentioned in library review and > >> > > tutorials, so I didn't know of it. What's the module's name? > >> > > >> > >> > >>> inspect is a module, inspect is the name. It is not a module for > >>> > >> > editing Python code per se, but it will help with the other part. > >> > >> > >> I don't think the OP wants to edit python code *objects*, rather he > >> wants to edit python *source* code programmatically. Inspect is not > >> the tool for this. > >> > > > > I didn't tell him to use inspect to edit python code, I said it was > > useful for the other part. The other part, as he mentioned on his > > email is: "find specific > > function definition, add another function call inside, find existing > > call". > > Sorry but I said "in *.py file", meaning that file isn't executed to > edit objects in memory. It's instead saved in modified form, possibly to > be edited by user. Guess it's a common task for visual GUI editors and > any visual programming tools. > By visual GUI editors I will assume GUI designer tools. These tend to not generate direct python code, glade-2 used to but glade-3 doesn't anymore. Other tools like XRCed generates xrc, wxGlade has an option to generate .xrc too, Qt Designer generates .ui and .qrc, Glade-3 generates .glade file, Gazpacho generates .glade, or a gazpacho format or gtkbuilder format. In all these, it is recommended to use something to work with the generated code, like libglade, wx.xrc and PyQt has tools to convert .ui and .qrc to python modules but they don't affect your custom code (it is also possible to load .ui using uic module). With this we come back to my first email, where I told you it is not recommended to generate direct python code, especially if you are doing the kind of things you just mentioned. If you still want to generate python code, from some other source, inspect can be helpful. > -- > > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From gagsl-py2 at yahoo.com.ar Tue Feb 26 21:49:41 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 27 Feb 2008 00:49:41 -0200 Subject: network programming: how does s.accept() work? References: <6d564fca-3884-4665-8a86-f7e658217a33@e60g2000hsh.googlegroups.com> <446482ef-1fd8-41dc-a8fd-44de8b51a8e8@o10g2000hsf.googlegroups.com> <379fcee4-15e0-48c2-863b-4b7458893cbe@h25g2000hsf.googlegroups.com> <711155c0-1305-41d3-895c-af9b8fe66f21@j28g2000hsj.googlegroups.com> Message-ID: En Tue, 26 Feb 2008 07:53:24 -0200, 7stud escribi?: > --- > When you surf the Web, say to http://www.google.com, your Web browser > is a client. The program you contact at Google is a server. When a > server is run, it sets up business at a certain port, say 80 in the > Web case. It then waits for clients to contact it. When a client does > so, the server will usually assign a new port, say 56399, specifically > for communication with that client, and then resume watching port 80 > for new requests. > --- > http://heather.cs.ucdavis.edu/~matloff/Python/PyNet.pdf You should *not* trust all you find on the Net... -- Gabriel Genellina From mattheww at chiark.greenend.org.uk Fri Feb 29 12:54:25 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 29 Feb 2008 17:54:25 +0000 (GMT) Subject: Nested module import clutters package namespace? References: Message-ID: <5Qm*0gH8r@news.chiark.greenend.org.uk> wrote: > I'd be grateful for help with a problem of package and module=20 > namespaces. The behaviour I observe is unexpected (to me), and I=20 > couldn't find the answer in the docs, the tutorial, or the mailing=20 > list archive. So here we go: > I have a package named 'pack'. Apart from the '__init__.py' file the=20 > directory contains two modules 'x.py' and 'y.py': > > pack/ > __init__.py > x.py > y.py > > The files have the following contents: > ==== __init__.py ==== > import x > ===================== > > ==== x.py =========== > import y > ===================== > > ==== y.py =========== > pass > ===================== > I then do > >>> import pack > This > (1) introduces variable 'x' bound to > in pack's namespace (expected) > (2) introduces variable 'q' bound to > in x's namespace (expected) > but also > (3) introduces variable 'y' bound to > in pack's namespace (*totally unexpected*) That's right, Python has behaved like this since packages were introduced. There's no doubt that this is intentional, but the state of the documentation is rather embarrassing. The reference manual's explanation of package imports consists largely of this reference: <> The referenced essay is over 10 years old and unsurprisingly somewhat out of date. This behaviour gets even more exciting when circular imports are involved. See for example message slrnbm2ajt.np4.stain at ozelot.stud.ntnu.no on this list. -M- From steve at REMOVE-THIS-cybersource.com.au Fri Feb 15 19:55:19 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 16 Feb 2008 00:55:19 -0000 Subject: Floating point bug? References: <6eba298e-6888-462a-afa7-54fae02c3dce@y5g2000hsf.googlegroups.com> <61ibo1F1uqso2U1@mid.uni-berlin.de> <188be6e9-bc05-4a72-924b-1de184980002@n58g2000hsf.googlegroups.com> <9b166b3d-89df-4f26-956a-abbd391167e7@i12g2000prf.googlegroups.com> Message-ID: <13rcd3nskgpv91d@corp.supernews.com> On Fri, 15 Feb 2008 10:55:47 -0800, Zentrader wrote: > I disagree with this statement > But that doesn't change the fact that it will expose the same > rounding-errors as floats do - just for different numbers. The > example used has no rounding errors. Of course it does. Three thirds equals one, not 0.9999, or 0.9999999999999999999999999999, or any other finite decimal representation. That's a rounding error, regardless of whether you are rounding in base 2 (like floats) or in base 10 (like Decimal does). > Also you can compare two > decimal.Decimal() objects for equality. With floats you have to test > for a difference less than some small value. That's a superstition. As a heuristic, it is often wise to lower your expectations when testing for equality. Since you often don't know how much rounding error will be introduced into a calculation, demanding that a calculation has zero rounding error is often foolish. But good advice becomes a superstition when it becomes treated as a law: "never test floats for equality". That's simply not true. For example, floats are exact for whole numbers, up to the limits of overflow. If you know your floats are whole numbers, and still writing something like this: x = 1234.0 y = 1000.0 + 200.0 + 30.0 + 4.0 if abs(x-y) < 1e-12: print "x and y are equal" then you are wasting your time and guilty of superstitious behaviour. Similarly for fractional powers of two. x = 1/2 + 1/4 + 1/8 + 1/16 y = 1.0 - 1/32 - 1/32 assert x == y -- Steven From gherzig at fmed.uba.ar Mon Feb 25 17:44:49 2008 From: gherzig at fmed.uba.ar (gherzig at fmed.uba.ar) Date: Mon, 25 Feb 2008 20:44:49 -0200 (ARST) Subject: Weird cgi error In-Reply-To: <254b27d2-5988-4d0c-8ca8-094a47455796@m23g2000hsc.googlegroups.com> References: <254b27d2-5988-4d0c-8ca8-094a47455796@m23g2000hsc.googlegroups.com> Message-ID: <16112.190.55.98.232.1203979489.squirrel@www.webmail.fmed.uba.ar> > >> This is some kind of crooked game, right? Your code works fine on a >> local server, and there's no reason why it shouldn't work just fine on >> yours either. All you are changing is the standard input to the process. >> >> Since you claim to have spotted this specific error, perhaps you'd like >> to explain just exactly how you came across it. I mean that's a pretty >> specific input to test with ... >> >> Frankly I am not sure you are telling the truth about the code behind >> that page. If you *are* then you'd better provide specifics: Python >> version, Apache version, httpd.conf file, and so on. April 1 is still >> over a month away. >> >> regards >> Steve >> >> PS: consider closing the > > > > > """ > > It's not a joke, honest :) > -- It just doesnt make sense to me. I guess we all agree that is not a python problem, because that code does actually nothing but showing the form. From __peter__ at web.de Sat Feb 16 04:10:33 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 16 Feb 2008 10:10:33 +0100 Subject: Help Parsing an HTML File References: <15f9198f-fa2a-4f4f-8f87-7402b03743e1@s13g2000prd.googlegroups.com> <47B693B9.3040007@behnel.de> Message-ID: Stefan Behnel wrote: > egonslokar at gmail.com wrote: >> I have a single unicode file that has descriptions of hundreds of >> objects. The file fairly resembles HTML-EXAMPLE pasted below. >> >> I need to parse the file in such a way to extract data out of the html >> and to come up with a tab separated file that would look like OUTPUT- >> FILE below. >> >> =====OUTPUT-FILE===== >> /please note that the first line of the file contains column headers/ >> ------Tab Separated Output File Begin------ >> H1 H2 DIV Segment1 Segment2 Segment3 >> Ros?H1-1 Ros?H2-1 Ros?DIV-1 Ros?SegmentDIV1-1 Ros?SegmentDIV2-1 >> ------Tab Separated Output File End------ >> >> =====HTML-EXAMPLE===== >> ------HTML Example Begin------ >> >> >>

Ros?H1-1

>>

Ros?H2-1

>>
Ros?DIV-1
>>
Ros?SegmentDIV1-1

>>
Ros?SegmentDIV2-1

>>
Ros?SegmentDIV3-1

>>
>>
>> >> >> ------HTML Example End------ > > Now, what ugly markup is that? You will never manage to get any HTML > compliant parser return the "segmentX" stuff in there. I think your best > bet is really going for pyparsing or regular expressions (and I actually > recommend pyparsing here). > > Stefan In practice the following might be sufficient: from BeautifulSoup import BeautifulSoup def chunks(bs): chunk = [] for tag in bs.findAll(["h1", "h2", "div"]): if tag.name == "h1": if chunk: yield chunk chunk = [] chunk.append(tag) if chunk: yield chunk def process(filename): bs = BeautifulSoup(open(filename)) for chunk in chunks(bs): columns = [tag.string for tag in chunk] columns += ["No Value"] * (6 - len(columns)) print "\t".join(columns) if __name__ == "__main__": process("example.html") The biggest caveat is that only columns at the end of a row may be left out. Peter From castironpi at gmail.com Wed Feb 20 21:23:55 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 20 Feb 2008 18:23:55 -0800 (PST) Subject: What's "the standard" for code docs? References: <47b69581$0$36393$742ec2ed@news.sonic.net> <96fc10f7-06fd-4e77-b38c-ec63e9b19341@s12g2000prg.googlegroups.com> <3878093e-e723-47f9-a7e3-fcfca012fa74@n77g2000hse.googlegroups.com> <26ae371c-0769-4434-9cd3-704ff8c81701@p43g2000hsc.googlegroups.com> <622efoF212v06U1@mid.uni-berlin.de> Message-ID: <01f6c079-4e56-4b6e-a4a5-d0eff34239fe@u69g2000hse.googlegroups.com> On Feb 20, 4:42?am, Marc 'BlackJack' Rintsch wrote: > On Tue, 19 Feb 2008 16:37:23 -0800, Preston ?Landers wrote: > > On Feb 19, 4:31 pm, castiro... at gmail.com wrote: > > > But after reading some of your other recent posts on other topics, I'm > > not confident that it was intended to make sense at all. > > Have a little bit patience, the bot is still in its early learning phase. ?;-) > > Ciao, > ? ? ? ? Marc 'BlackJack' Rintsch >>> bayesian= Bayesian() >>> bayesian.train( 'http://groups.google.com/group/comp.lang.python/' ) Training complete. 1.3 seconds elapsed. >>> bayesian.run() Everything! Nobody cares. (setting person.care= 0.0 for person in people) Processing... That's not too bad actually. Where's the bar? >>> From bbxx789_05ss at yahoo.com Sat Feb 16 22:27:56 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Sat, 16 Feb 2008 19:27:56 -0800 (PST) Subject: class static variables and __dict__ References: Message-ID: On Feb 16, 5:03?pm, Zack wrote: > Dustan wrote: > > On Feb 16, 4:40 pm, Zack wrote: > >> what method can you use on x to find all available > >> attributes for that class? > > >>>> class Foo(object): > > ? ?bar = "hello, world!" > > ? ?def __init__(self, baz): > > ? ? ? ? ? ?self.baz = baz > > >>>> x = Foo(42) > > >>>> x.__dict__.keys() # Does not include bar > > ['baz'] > > >>>> dir(x) # Includes bar plus some methods > > ['__class__', '__delattr__', '__dict__', '__doc__', > > '__getattribute__', '__hash__', '__init__', '__module__', '__new__', > > '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', > > '__weakref__', 'bar', 'baz'] > > I knew there was something simple I was forgetting. > Thanks > dir() doesn't do it either: ----- dir( [object]) Without arguments, return the list of names in the current local symbol table. With an argument, attempts to return a list of valid attributes for that object. This information is gleaned from the object's __dict__ attribute, if defined, and from the class or type object. ***The list is not necessarily complete.*** If the object is a module object, the list contains the names of the module's attributes. If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases. Otherwise, the list contains the object's attributes' names, the names of its class's attributes, and recursively of the attributes of its class's base classes. The resulting list is sorted alphabetically. For example: Note: Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. -------------- In other words, dir() is the most preposterous function in python. From gagsl-py2 at yahoo.com.ar Wed Feb 13 02:14:53 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 13 Feb 2008 05:14:53 -0200 Subject: Difficulty with "inconsistent use of tabs and spaces in indentation" in file called References: <3a894604-6bbb-4482-aacc-cb36bc6e5de5@s13g2000prd.googlegroups.com> <18224a36-a55d-41be-8209-88d06f116a1c@f10g2000hsf.googlegroups.com> <7ac9c5f5-0e8e-498d-9be1-4113cb07eaa0@f10g2000hsf.googlegroups.com> Message-ID: En Tue, 12 Feb 2008 22:57:01 -0200, ibloom escribi?: > On Feb 11, 9:10?pm, "Gabriel Genellina" > wrote: >> >> >> : inconsistent use of tabs and spaces in indentation >> >> Traceback (most recent call last): >> >> ? File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ >> >> python2.4/site-packages/py2app/py2app/util.py", line 13, in >> >> find_version >> >> ? ? ast = compiler.parseFile(fn) >> >> > Put a print statement just above that line, to see which file > >> triggers the error. >> > > Gabriel, your the master. > Of course I didn't understand that py2app was trying to compile my own > python source code and when I switched to Xcode as my new editor, I > started mixing in tabs. So was in fact my code. All I had to > do was change my preferences in Xcode, to generate spaces instead of > tabs, remove all of the offending tabs and voila. You've ended days of > frustrations. Thank you. Glad to be of any help. Note that all the clues were on the traceback. When people here insist that all error reports should come with the complete stack trace, it isn't because they want to be annoying, but because it's really useful... -- Gabriel Genellina From bearophileHUGS at lycos.com Tue Feb 12 19:53:25 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 12 Feb 2008 16:53:25 -0800 (PST) Subject: ways to declare empty set variable References: <56a14$47b1a306$839b8704$9583@news2.tudelft.nl> <5099c$47b1a77b$839b8704$11089@news2.tudelft.nl> <7xhcgd7tof.fsf@ruckus.brouhaha.com> <719e7c26-7d52-4b78-875c-fc7d5ca32f4e@s19g2000prg.googlegroups.com> <874pcdzsho.fsf@benfinney.id.au> <288aaa1d-fd52-4b8e-98d2-15a68f6da946@l32g2000hse.googlegroups.com> <87tzkdyax9.fsf@benfinney.id.au> Message-ID: <91efd5aa-0220-41db-81ca-18cdbc1e68a8@m34g2000hsb.googlegroups.com> Ben Finney: > Generator literals do not require the > parens at all. However, the syntax of where the generator literal > *appears* can make it necessary to explicitly group the expression > using parens. Have you taken a look at Boo? In Python this isn't possible: s = char for char in string.digits You need ( ) there, while in Boo they aren't necessary there. Bye, bearophile From mailmaverick666 at gmail.com Tue Feb 26 02:06:12 2008 From: mailmaverick666 at gmail.com (rishi pathak) Date: Tue, 26 Feb 2008 12:36:12 +0530 Subject: running a daemon in python In-Reply-To: <910313af0802252236x36e50d4di4f39d9e45d26d6fc@mail.gmail.com> References: <910313af0802252236x36e50d4di4f39d9e45d26d6fc@mail.gmail.com> Message-ID: <180b672e0802252306j448113beua56aad84df22cb11@mail.gmail.com> Use the function goDaemon just before starting the server loop: ###############Begin Module####################### import os import sys # Default daemon parameters. # File mode creation mask of the daemon. UMASK = 0 # Default working directory for the daemon. WORKDIR = "/" # Default maximum for the number of available file descriptors. MAXFD = 1024 # The standard I/O file descriptors are redirected to /dev/null by default. if (hasattr(os, "devnull")): REDIRECT_TO = os.devnull else: REDIRECT_TO = "/dev/null" def goDaemon(): try: pid = os.fork() except OSError, e: raise Exception, "%s [%d]" % (e.strerror, e.errno) if (pid == 0): # The first child. os.setsid() try: pid = os.fork() # Fork a second child. except OSError, e: raise Exception, "%s [%d]" % (e.strerror, e.errno) if (pid == 0): # The second child. os.chdir(WORKDIR) os.umask(UMASK) else: os._exit(0) else: os._exit(0) # Exit parent of the first child. import resource maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1] if (maxfd == resource.RLIM_INFINITY): maxfd = MAXFD for fd in range(0, maxfd): try: os.close(fd) except OSError: # ERROR, fd wasn't open to begin with (ignored) pass os.open(REDIRECT_TO, os.O_RDWR) # standard input (0) os.dup2(0, 1) # standard output (1) os.dup2(0, 2) # standard error (2) return(0) ###############End Module####################### On Tue, Feb 26, 2008 at 12:06 PM, bharath venkatesh wrote: > hi .. > hi i want a program to start running as daemon in background .. my > program is server listen to a client ... so i want to make that program run > as daemon .. when i execute the program the program for ex server.py it > should automatically start running as daemon in the background even if i > close the terminal it shouldn't stop executing.. (right now if i close the > terminal the process exits) can any one tell how to do it in python as i > have implemented the server in python ... > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Regards-- Rishi Pathak -------------- next part -------------- An HTML attachment was scrubbed... URL: From dont at spamon.me Mon Feb 4 19:37:46 2008 From: dont at spamon.me (USCode) Date: Mon, 04 Feb 2008 16:37:46 -0800 Subject: Client side GUI-like web framework ? In-Reply-To: References: <4f7d69d7-83ef-4492-900b-fdfb36ab48f0@p69g2000hsa.googlegroups.com> Message-ID: Michael L Torrie wrote: > > But it is served up in the firefox web browser. A good example is: > > http://www.faser.net/mab/chrome/content/mab.xul > That's pretty slick, but unfortunately then you're locked into only the Firefox web browser, which many folks don't use. You're trading OS lock-in for browser lock-in. From pavlovevidence at gmail.com Fri Feb 15 15:20:05 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 15 Feb 2008 12:20:05 -0800 (PST) Subject: Turn off ZeroDivisionError? References: <63d2e7d1-aa26-4ddc-9d12-42ae636104c1@s37g2000prg.googlegroups.com> <13qunlu5nrva731@corp.supernews.com> <13qusltq0v8vt39@corp.supernews.com> <13qv4dh7fpe0e93@corp.supernews.com> <47b50ed0$0$36357$742ec2ed@news.sonic.net> Message-ID: On Feb 14, 11:09 pm, John Nagle wrote: > You also need to think about how conditionals interact with > quiet NANs. Properly, comparisons like ">" have three possibilities: > True, False, and "raise". Many implementations don't do that well, > which means that you lose trichotomy. "==" has issues; properly, > "+INF" is not equal to itself. I'm pretty sure it is. It certainly is on my machine at the moment: >>> float(3e300*3e300) == float(2e300*4e300) True Are you confusing INF with NAN, which is specified to be not equal to itself (and, IIRC, is the only thing specified to be not equal to itself, such that one way to test for NAN is x!=x). > For Python, I'd suggest throwing a Python exception on all errors > recognized by the FPU, except maybe underflow. If you're doing > such serious number-crunching that you really want to handle NANs, > you're probably not writing in Python anyway. Even if that were entirely true, there are cases where (for example) you're using Python to glue together numerical routines in C, but you need to do some preliminary calculations in Python (where there's no edit/compile/run cycle but there is slicing and array ops), but want the same floating point behavior. IEEE conformance is not an unreasonable thing to ask for, and "you should be using something else" isn't a good answer to "why not?". Carl Banks From sjmachin at lexicon.net Mon Feb 4 18:09:48 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 4 Feb 2008 15:09:48 -0800 (PST) Subject: Mysterious xml.sax Encoding Exception References: <6edad0b6-1d4a-46ec-a6c2-c8caed3089c3@f47g2000hsd.googlegroups.com> Message-ID: <47502452-36b7-4598-b156-0ec91a86a237@c23g2000hsa.googlegroups.com> On Feb 5, 9:02 am, JKPeck wrote: > On Feb 2, 12:56 am, Jeroen Ruigrok van der Werven > nomine.org> wrote: > > -On [20080201 19:06], JKPeck (JKP... at gmail.com) wrote: > > > >In both of these cases, there are only plain, 7-bit ascii characters > > >in the xml, and it really is valid utf-16 as far as I can tell. > > > Did you mean to say that the only characters they used in the UTF-16 encoded > > file are characters from the Basic Latin Unicode block? > > > It appears that the root cause of this problem is indeed passing a > Unicode XML string to xml.sax.parseString with an encoding declaration > in the XML of utf-16. This works with the standard distribution on > Windows. It did NOT work for me with the standard 2.5.1 Windows distribution -- see the code + output that I posted. > It does not work with ActiveState on Windows even though > both distributions report > 64K for sys.maxunicode. > > So I don't know why the results are different, but the problem is > solved by encoding the Unicode string into utf-16 before passing it to > the parser. From martin at v.loewis.de Sun Feb 24 13:53:59 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 24 Feb 2008 19:53:59 +0100 Subject: _struct in Python 2.5.2 In-Reply-To: References: Message-ID: <47c1bd47$0$2715$9b622d9e@news.freenet.de> > I found out that there has been a file named _struct.so in 2.5.1 but > it has disappeared in 2.5.2. With no package available for downgrading > to 2.5.1 and no idea how to resolve this I am stuck at this point. > > Any help appreciated. Where did you get your copy of Python 2.5.2 from, and how did you install it? _struct should be there; if it isn't, something went wrong during the installation. Regards, Martin From steve at holdenweb.com Thu Feb 28 08:28:06 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 28 Feb 2008 08:28:06 -0500 Subject: call by reference howto???? In-Reply-To: <398ef888-0a87-4ff3-990c-3197417cadec@z17g2000hsg.googlegroups.com> References: <47c5f9b8$0$21935$9b4e6d93@newsspool2.arcor-online.net> <85463eba-4380-41cb-8e46-8b73909abe22@f47g2000hsd.googlegroups.com> <398ef888-0a87-4ff3-990c-3197417cadec@z17g2000hsg.googlegroups.com> Message-ID: <47C6B6E6.3060103@holdenweb.com> castironpi at gmail.com wrote: > On Feb 27, 10:38 pm, Dan Bishop wrote: > >> What exactly are you wanting to do? > > I'm having a hard time considering your question in the general case. > I'm thinking of too many cases, the details of which are relevant to > the answer, to even subdivide them. My specialty is specific > application; I know ten tricks that apply 10% of the time each. I can > show you all of them but not at once! When you have nothing to say it's normally best not to say it. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From DustanGroups at gmail.com Sun Feb 24 07:18:31 2008 From: DustanGroups at gmail.com (Dustan) Date: Sun, 24 Feb 2008 04:18:31 -0800 (PST) Subject: iter(lambda:f.read(8192),'') References: Message-ID: <380e0817-eb71-4129-ae78-28890cd38775@f47g2000hsd.googlegroups.com> On Feb 24, 5:11 am, gert wrote: > what is the difference between iter(lambda:f.read(8192), ') and > iter(f.read(8192),'') ? One does not work, and one is syntactically incorrect: >>> iter(f.read(8192),'') Traceback (most recent call last): File "", line 1, in iter(f.read(8192),'') TypeError: iter(v, w): v must be callable >>> iter(lambda:f.read(8192), ') SyntaxError: EOL while scanning single-quoted string To clarify: f.read(8192) returns the next 8192 bytes of the file in a string, or whatever is leftover, or an empty string when the file is exhausted. lambda: f.read(8192) is a function that will return the next 8192 bytes of the file every time it is called. So iter(f.read(8192),'') is evaluated as iter(some_string, ''). When iter receives two arguments, it expects the first to be a function, not a string. iter(lambda:f.read(8192), '') (what you probably meant) is what it looks like: iter(some_func, ''). From steve at holdenweb.com Fri Feb 15 12:46:36 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 15 Feb 2008 12:46:36 -0500 Subject: Looking for a Python Program/Tool That Will Add Line Numbers to a txt File In-Reply-To: References: <4BRsj.10199$Ch6.5665@newssvr11.news.prodigy.net> <446814ba-184e-44ad-bda9-05c1817af950@72g2000hsu.googlegroups.com> Message-ID: W. Watson wrote: > Thanks. I found this to work: > > input_file=open('junkin.txt','r') > output_file=open('junkout.txt','w') > for (line_cnt, each_line) in enumerate(input_file): > output_file.write('%4d '%(line_cnt+1)+each_line) You can improve this slightly by using string formatting more fully: output_file.write("%4d %s" % (line_ct+1, each_line)) > output_file.close() > input_file.close() > regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From jgardner at jonathangardner.net Tue Feb 26 15:49:11 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Tue, 26 Feb 2008 12:49:11 -0800 (PST) Subject: Asynchronous urllib (urllib+asyncore)? Message-ID: <84ad9131-c09d-4d63-993b-f607563afa3c@k2g2000hse.googlegroups.com> So, I ran into a problem that I would like to write as little code as possible to solve. The problem is that I would like to send out a bunch of HTTP requests simultaneously, using asynchronous techniques, and then do stuff with the results in parallel. Think of something like Google's map-reduce. It sounds like this would be something someone else has done before. I searched google, but I don't think there is any discussion anywhere of anyone doing something like this. I am sure Twisted folks can code this up in 2 lines or less, or it probably already exists there by default. But I need this to exist in a non-asynchronous environment. I can't let Twisted take over everything. So, has someone done something like this? Is it something where I can bring the urllib and asyncore together? Or is it much more involved? From sjmachin at lexicon.net Mon Feb 11 17:34:18 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 11 Feb 2008 14:34:18 -0800 (PST) Subject: packing greyscale values References: <71215618-85cd-4ad5-9e95-354f9859fc4d@s37g2000prg.googlegroups.com> Message-ID: On Feb 11, 9:11 pm, Peter Otten <__pete... at web.de> wrote: > jimgardener wrote: > > hi > > i am getting value of a pixel of a greyscale image using PIL's > > image.getdata and need to pack it as an int as below > > > ie greyvalues > > 127 , 56 , 135 , 99 , 102 , 101 , 146 , 112 , 155 , 154 , 112 , 169 > > > should become > > -4473925, -8289919, -4144960, -5789785, -5592406, -5658199 ,-3684409, > > -5131855, -3289651,-3355444, -5131855, -2763307 > > > (i got these values using java's BufferedImage class..)I would like to > > know if there is a way to do the conversion in python.(.i need 'these > > 'for some calculations) > > Judging from > > >>> hex(0x100000000 - 4473925) > '0xffbbbbbb' > >>> 0xbb > > 187 > > -4273925 indeed seems to denote a gray value, but the lighter 187 rather > than 127. Are you sure the lists you give belong to the same image? > > Peter Let Y = Java-derived numbers (187, etc) and X = PIL-derived numbers (127, etc) Y approx = 0.75 * X + 90 What the underlying cause of this relationship is, I have not a clue. Cheers, John From sajmikins at gmail.com Sun Feb 24 19:52:21 2008 From: sajmikins at gmail.com (Simon Forman) Date: Sun, 24 Feb 2008 16:52:21 -0800 (PST) Subject: How to make "rainbow" RGB values? Message-ID: <80b75e15-787a-4369-b7fe-792131143d90@s12g2000prg.googlegroups.com> Hey all, I want to map an int to a color on a rainbow spectrum, i.e. for an int n in the range 0..N, low values (near 0) should map to the red end, and high values (near N) to the blue/violet end. The return values should be R, G, B tuples (well, "#xxxxxx" color codes, but that's not the hard part.) The trouble I'm having is in coming up with a good way to generate color values that approximates the "ROY G BIV" rainbow spectrum. This is just a simple, non-scientific, non-photographic application, nothing fancy. I've tried a simple scheme of overlapping sines, but this resulted in too much red and blue, and no indigo/violet. Any suggestions? I'm searching on the web now but not coming up with much, so I thought I'd ask here. TIA, ~Simon Here's the sinecode I tried: def g(n): ''' map sine [-1.0 .. 1.0] => color byte [0 .. 255] ''' return 255 * (n + 1) / 2.0 def f(start, stop, N): interval = (stop - start) / N for n in range(N): coefficient = start + interval * n yield g(sin(coefficient * pi)) n = 150 RED = f(0.5, 1.5, n) GREEN = f(1.5, 3.5, n) BLUE = f(1.5, 2.5, n) RGBs = [('#%02x%02x%02x' % rgb) for rgb in zip(RED, GREEN, BLUE)] From robert.kern at gmail.com Mon Feb 25 16:02:50 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 25 Feb 2008 15:02:50 -0600 Subject: Python code for 2.5 and 2.4? In-Reply-To: <28a84535-483d-461d-828d-bb9a38be19f0@v3g2000hsc.googlegroups.com> References: <28a84535-483d-461d-828d-bb9a38be19f0@v3g2000hsc.googlegroups.com> Message-ID: Joseph Turian wrote: > I was given code that was written for python 2.5, and uses simple > functions like 'all' which are not present in 2.4 > > I want to make the code 2.4 compatible. What is the best way to do > this? If it's a single file, put something like the following code near the top. If you have multiple modules, put it into a separate module, say compatibility.py, and change the other modules to import these functions from there. import sys if sys.version_info[:2] < (2,5): def all(*args): ... def any(*args): ... else: # Only bother with this else clause and the __all__ line if you are putting # this in a separate file. import __builtin__ all = __builtin__.all any = __builtin__.any __all__ = ['all', 'any'] > If I define function 'all', then won't I break 2.5 compatability? No. Defining a function named the same thing as a builtin function will not break anything. You just wouldn't be using the efficient implementation already in Python 2.5. Using the if: else: suite above lets you have both at the expense of some clunkiness. -- 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 software at ginstrom.com Sat Feb 23 22:32:25 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Sun, 24 Feb 2008 12:32:25 +0900 Subject: Hyphenation module PyHyphen-0.3 released In-Reply-To: References: <47c07478$0$26904$6e1ede2f@read.cnntp.org><9c37ed98-907d-4102-96b2-78867cd351e2@o10g2000hsf.googlegroups.com> Message-ID: <01e001c87695$e0197ab0$0203a8c0@MOUSE> > On Behalf Of Max Erickson > the easy way to do this might be to find(in your mingw /lib > directory) and copy or rename libmsvcr71.a and libmsvcr71d.a > into libmsvcrt.a and libmsvcrtd.a (backing up the originals > if desired). If the MingW you have installed doesn't provide > the appropriate runtime, you would have to track that down. Here's another way. Go to /MinGW/lib/gcc/mingw32/3.4.2/spec, and modify the libgcc directive as follows: *libgcc: %{mthreads:-lmingwthrd} -lmingw32 -lgcc -lmoldname -lmingwex -lmsvcr71 Regards, Ryan Ginstrom From fuzzyman at gmail.com Wed Feb 6 19:17:15 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Wed, 6 Feb 2008 16:17:15 -0800 (PST) Subject: Is there a way to use .NET DLL from Python References: <85706ba0-8c24-4324-9a79-98c97fc802db@e4g2000hsg.googlegroups.com> <6c2845aa-aec5-4b75-852a-551b9cd1d6ab@f10g2000hsf.googlegroups.com> Message-ID: On Feb 6, 9:59 pm, "Luis M. Gonz?lez" wrote: > On Feb 6, 6:27 pm, Huayang Xia wrote: > > > Hello All, > > > I have several .NET DLL (I have no source code for them), is there > > anyway to use them from python instead of from C#. > > > Thanks, > > Huayang > > I used to put my .dll files into the .DLL folder, so I could simply > import them as I would with any other python module. > But since I started using Ironpython 2.0 Alpha* this doesn't work > anymore... > Any hint? The rule is probably still that the DLLs must be in a directory on sys.path for the interpreter to find them. Try adding the directory containing the assemblies to sys.path and see if you can add references to them. Michael Foord http://www.manning.com/foord > > Luis From greg at cosc.canterbury.ac.nz Mon Feb 18 00:23:16 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Mon, 18 Feb 2008 18:23:16 +1300 Subject: Solve a Debate In-Reply-To: <82ol85-0o5.ln1@darkstargames.dnsalias.net> References: <82ol85-0o5.ln1@darkstargames.dnsalias.net> Message-ID: <61sjcbF20ug9dU1@mid.individual.net> Wolfgang Draxinger wrote: > Somehow you seem to think, that a lookup table will require more > resources (memory I guess you thought) than a sequence of > comparisons. However you didn't take into account, that the > program code itself requires memory, too (for the operation > codes). In Python, there's the additional twist that for lookup tables based on a mutable type, such as a dictionary, you need to execute code to build the dictionary. So you end up using very roughly twice the memory -- for the code to build the dictionary, and the dictionary itself. If the dictionary isn't too huge, and it's looked up many times during each run of the program, the extra speed of the dict lookup is probably worth the overhead of creating it. If the dict is very large, and is consulted relatively few times in a given run, then it might well be faster and not use too much more memory to use a tree (NOT a linear sequence!) of if-else statements in the code. You could also consider loading the dict from some other form, such as a pickle, instead of creating it using code. This would use less memory, although probably would take roughly the same time to set up the table. For extremely large infrequently-used tables, it's probably better to look at not loading the whole table into memory at all, and keeping it in some kind of external indexed structure such as a b-tree, relational database, etc. In other languages, the tradeoffs will be completely different. E.g. in C, if you can describe the table entirely with static data, it'll be very fast to load and incur no overhead for code to create it at all. Also, with demand-paging out of the executable file, and infrequent lookups, only parts of the table will actually get loaded anyway. -- Greg From castironpi at gmail.com Wed Feb 13 16:43:30 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 13 Feb 2008 13:43:30 -0800 (PST) Subject: XML pickle Message-ID: <686a4012-1c9e-456e-973c-c1e396f4c060@s8g2000prg.googlegroups.com> Readability of the Pickle module. Can one export to XML, from cost of speed and size, to benefit of user-readability? It does something else: plus functions do not export their code, either in interpreter instructions, or source, or anything else; and classes do not export their dictionaries, just their names. But it does export in ASCII. Pickle checks any __safe_for_unpickling__ and __setstate__ methods, which enable a little encapsulating, but don't go far. At the other end of the spectrum, there is an externally-readable datafile: abc 123
Classes can be arranged to mimic this hierarchy: class XMLable: def __init__( self, **kwar ): self.attrs= kwar class Workbook( XMLable ): cattrs= { 'xmlns': "urn:schemas-microsoft-com:office:spreadsheet", 'xmlns:ss': "urn:schemas-microsoft-com:office:spreadsheet" } class Worksheet( XMLable ): cattrs= { 'name': 'ss:Name' } class Table( XMLable ): pass class Row( XMLable ): pass class Cell( XMLable ): pass class Data( XMLable ): cattrs= { 'type': 'ss:Type' } data= Data( content= 'abc', type= 'String' ) cell= Cell( data= data ) row= Row( cells= [ cell ] ) table= Table( rows= [ row ] ) sheet= Worksheet( table= table, name= "Sheet1" ) book= Workbook( sheets= [ sheet ] ) (These might make things cleaner, but are not allowed: #data= Data( 'abc', 'ss:Type'= 'String' ) #sheet= Worksheet( table= table, 'ss:Name'= "Sheet1" ) For keys can only be identifiers in keyword argument syntax.) How close to this end can the standard library come? Is it more prevalent than something else that's currently in it? What does the recipie look like to convert this to XML, either using import xml or not? import pickle print( pickle.dumps( book ) ) is not quite what I have in mind. I guess I'm not convinced that 'is currently in use' has always been or even is the standard by which standard library additions are judged. If it's not, then I hold that XML is a good direction to go. Will core developers listen to reason? Does +1 = +1? From trades at none.com Fri Feb 8 10:31:09 2008 From: trades at none.com (jack trades) Date: Fri, 8 Feb 2008 09:31:09 -0600 Subject: How to autorun a python script when a specific user logs on? References: <47a81708$0$16675$4c368faf@roadrunner.com> <51d3f6e8-a6c7-485e-9bb5-313bc7a1ddc4@q21g2000hsa.googlegroups.com> <47a8a44c$0$30679$4c368faf@roadrunner.com> Message-ID: <47ac75d3$0$6120$4c368faf@roadrunner.com> "Wolfgang Draxinger" wrote in message news:gv5u75-rid.ln1 at darkstargames.dnsalias.net... > jack trades wrote: > > > Honestly I never even thought of that, it just sounded like a > > fun, and easy, > > project to put my mediocre programming skills to some use. > > However his main concern is internet predators (too much > > Dateline I think) not porn, I should > > have worded it differently in the OP. > > Technically I would not use a keylogger for this. Your > implementation can be circumvented easyly anyway, and every > spyware detection tool will report the hooks immediately. > However I think that tool could do nicely for application > documentation :-) > > To protect the children from predators I'd use transparent > proxies, to analyze all textual traffic for specific statistical > patters, kinda like a Bayes Spam filter, and raise an alarm as > soon something unusual, eventually in combination with some > keywords happens. > > This includes majorly 3 protocols: HTTP, SMTP and IRC. e-mails > should be prefiltered anyway, alone for all the spam. > > Such a system is best installed on a dedicated machine, e.g. a > Linux based router/gateway, that transparently sends all HTTP, > SMTP and IRC traffic through the analyzers. This cannot be > circumvented, as long the kids don't know the root password for > the gateway. > > If you're still up on making screenshots, I'd recommend to > install a VNC deamon, as a _system service_(!), to which the > alarm action program connects to make screenshots. > > Wolfgang Draxinger > -- > E-Mail address works, Jabber: hexarith at jabber.org, ICQ: 134682867 Thanks for the suggestion. I can't believe I didn't think of this. I just installed Kubuntu on one of his old computers (I'm trying to get him to convert to Linux :) and this would work perfectly, especially since I don't really expect him to use the linux box. Trying to get a Windoze user to switch to linux is like pulling teeth. Jack Trades From joe at example.com Sat Feb 2 10:34:03 2008 From: joe at example.com (Trevor Hennion) Date: Sat, 2 Feb 2008 15:34:03 +0000 (UTC) Subject: xmlrpclib, testing server presence References: Message-ID: On Sat, 02 Feb 2008 00:22:15 -0800, rocco.rossi wrote: > I'm employing xmlrpclib for a project at work, and I must say that I'm > quite impressed with its effectiveness and ease of use. > > However, I was recently doing some tests when I realized that if the > server was down, the client quite simply hanged (no use of "try ... > except" here) with no error or tracebacks or exceptions whatsoever. > > Is there some way in Python of "testing" the presence of the server on > the other end, so as to avoid this situation? > > Thank you. Hi, Could you test for a socket timeout?: socket.setdefaulttimeout(20.0) # timeout = 20.0 secs regards Trevor http://www.infocentrality.co.uk From lasses_weil at klapptsowieso.net Wed Feb 27 07:24:37 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Wed, 27 Feb 2008 13:24:37 +0100 Subject: Documentation - which format In-Reply-To: <1280d0ce-ca33-4cf3-b661-8df4f362fd7e@e6g2000prf.googlegroups.com> References: <0001HW.C3EA559A00413F8FB01AD9AF@news.individual.de> <1280d0ce-ca33-4cf3-b661-8df4f362fd7e@e6g2000prf.googlegroups.com> Message-ID: <47c55738$0$25504$9b4e6d93@newsspool1.arcor-online.net> grflanagan at gmail.com wrote: > Definitely ReST. See http://rst2a.com/ > Hey, this is sweet! Thanks for that. /W From timr at probo.com Sat Feb 9 22:13:18 2008 From: timr at probo.com (Tim Roberts) Date: Sun, 10 Feb 2008 03:13:18 GMT Subject: Error on Python References: <2713302a-dade-4c5d-9eba-eb73f4f03d6f@s12g2000prg.googlegroups.com> Message-ID: maehhheeyy wrote: >Hi, right now I'm using Python and Multicast. I have the code for >Multicast receiver on Python but I keep getting this error; > >File "", line 1, in bind >error: (10049, "Can't assign requested address") > >The error is coming from this line; >sock.bind ((MCAST_ADDR, MCAST_PORT)) > >Can anyone please help me solve this problem? Where did you get the multicast module? Are you trying to do TCP multicast? What is the address you are trying to use? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From cwitts at gmail.com Wed Feb 20 03:03:36 2008 From: cwitts at gmail.com (Chris) Date: Wed, 20 Feb 2008 00:03:36 -0800 (PST) Subject: how to finish a while loop... References: <4b89dd2b-782c-4d07-ac6f-d5ae4b3b1b4c@s12g2000prg.googlegroups.com> <055ec51d-2119-45fd-9284-e70d88449a1a@j28g2000hsj.googlegroups.com> <772d5e87-0e0e-485b-b35f-0f9e09a3076f@i12g2000prf.googlegroups.com> <61826599-c744-4b62-983a-c3d5e5f83081@u69g2000hse.googlegroups.com> Message-ID: On Feb 20, 3:42 am, richie wrote: > On Feb 20, 9:35 am, icarus wrote: > > > > > > To the original poster.... what environment are you running this in? > > > Linux. Xubuntu if that matters. > > > > When I put your program in notepad and run it from the windows command > > > prompt it works. > > > yeah yeah...same here. > > After I got the tip that it actually worked, I went into the eclipse > > directory where the program lives, ran it there from the shell, and it > > worked. Meaning, I didn't modify anything on the file itself (by > > accident or on purpose). > > > > But when I paste it into eclipse and run it > > > eclipse's console, it doesn't work because answer seems to have a > > > stray '\r' carriage return (CR) and therefore the comparison to 'no' > > > fails. > > > I get no 'compile' errors there. > > I get regular execution but it just doesn't change the > > condition to False at the very end. > > Therefore it loops forever. I used other values like zeros > > and ones to make sure I could print the values when the interpreter > > got down to that line. Everything checked. Just didn't change the > > condition on the main loop. > > I've changed this code a little. > condition = True > while ( condition ): > try: > integer_one = int ( raw_input( "Please enter an integer: " ) ) > integer_two = int ( raw_input( "Please enter the second > integer: " ) ) > division = integer_one / integer_two > except( ZeroDivisionError ): > print "\nDivision by zero detected" > except( ValueError ): > print "\nYou didn't enter an integer" > else: > print "The result is", division > answer = raw_input("Do you want to try again (yes or no)? ") > print answer > #answer="no" > if answer == "yes": > condition=True > elif answer == "no": > condition=False > print "Good bye, you don't want to continue" > print condition > And i got this result in eclipse3.2: > Please enter an integer: 8 > Please enter the second integer: 4 > The result is 2 > Do you want to try again (yes or no)? no > no > Good bye, you don't want to continue > True > Please enter an integer: > > it seems the input "no" in eclipse's console to answer won't equal the > "no" we compare. > And when I remove the comment and I get this result: > Please enter an integer: 8 > Please enter the second integer: 4 > The result is 2 > Do you want to try again (yes or no)? no > no > Good bye, you don't want to continue > False strip and lowercase your answer for better comparison checking. From joshua.r.english at gmail.com Sun Feb 17 19:34:27 2008 From: joshua.r.english at gmail.com (Josh English) Date: Sun, 17 Feb 2008 16:34:27 -0800 Subject: Developing a Package with Sub Packages Message-ID: I have created a group of scripts to manage an XML-based database. I'd like to make it into a proper package that will let me keep track of the code. I have a lot of files that are similar in name and they just get crowded in one folder. Here's a sample of the file structure: IMS/ IMS/__init__.py IMS/Config.py IMS/imsdefaults.cfg IMS/local.txt IMS/Data/ IMS/Data/stories.xml IMS/Story/ IMS/Story/__init__.py IMS/Story/StoryCreator.py When the IMS/__init__.py file is loaded, it creates the IMS/Data/ folder and if there are no xml files, it creates them and fills them in with some default values. The IMS/Config.py has a subclass of the ConfigParser, and reads the imsdefaults.cfg and local.txt files. When I run StoryCreator, buried in it's own package (that imports IMS) the data folder is created inside the Story folder, and I get an error message stating the ConfigParser object could not find the imsdefaults.cfg file. Here's what I think is happening: IMS/__init__.py uses os.getcwd() to establish the path to the data folder and the files inside of it. When I run StoryCreator, os.getcwd() returns the story folder. If I'm right, how can I get the IMS/__init__.py module to use relative paths to its own module, and not the current working directory the os module provides? This could also solve the problem with Config.py, I think. Thanks Josh English http://joshenglish.livejournal.com From emachele at gmail.com Fri Feb 22 07:35:30 2008 From: emachele at gmail.com (elfrida8) Date: Fri, 22 Feb 2008 04:35:30 -0800 (PST) Subject: MAKE MONEY FAST USING EGOLD!! Message-ID: <76103237-f6ad-48df-b12c-5e66be7d7bcc@c33g2000hsd.googlegroups.com> You Can Laugh at Money Worries - if You Follow This Simple Plan! This is an opportunity for people who would like to work at home and have computer experience and are willing to invest time to get the lifestyle you have been wanting! READ ON: Read this entire message carefully! (Print it out or download it.) I found this on a bulletin board and decided to try it. A little while back, I was browsing through news groups and came across an article similar to this that said you could make thousands of dollars within weeks with only an initial investment of $6.00! So I thought, Yeah right, this must be a scam, but like most of us, I was curious, so I kept reading. Anyway, it said that you send only $1.00 to each of the 6 Egold accounts stated in this article. You then place your name and address at the bottom of the list at the #6rd position and email it to your friends as well as post this message (with your email address in the list) to at least 200 newsgroups. (There are thousands) No catch, that was it. So after thinking it over, and talking to a few people first, I thought about trying it. I figured, what have I got to lose except $6.00, right? So I invested the measly $6.00. Well GUESS WHAT!! Within days, I started getting money coming into my Egold account! I was shocked! I figured it would end soon, but the money just kept coming in. In my first week, I made about $25.00, which means that 12 people joined the group after they saw my posted messages. By the end of the second week I had made a total of over $1000.00! In the third week I had over $10,000.00 and it's still growing. This is now my fourth week and I have made a total of just over $42,000.00 and it?s still coming in rapidly. It's certainly worth $6.00, and the few minutes it took to join Egold. I have spent more than that on the lottery! Let me tell you how this works and most importantly, why it works. Also, make sure you print a copy of this article NOW, so you can get the information off of it, as you need it. I promise you that if you follow the directions EXACTLY, that you will start making more money than you thought possible by doing something so easy! SUGGESTION: Read this entire message carefully! (Print it out or download it.) Follow the simple directions and watch the money comes in! It's that easy. It's legal. And, your investment is only $6.00. IMPORTANT: This is not a rip-off; it is not indecent; it is not illegal; and it is virtually no risk-it really works! If all of the following instructions are adhered to, you will receive extraordinary dividends. AGAIN, PLEASE NOTE: Follow these directions EXACTLY, and $20,000 or more can be yours in 4 to 6 weeks. This program remains successful because of the honesty and integrity of the participants. Please continue its success by carefully adhering to the instructions. In this business your product is not solid and tangible, it's a service. You are in the business of developing Mailing Lists. Many large corporations are happy to pay big bucks for quality lists. However, the money made from the mailing lists is secondary to the income, which is made from people like you and me asking to be included in that list. Here are the 4 easy steps to success: STEP 1: Take a few minutes to join Egold: here is the link: https://www.e-gold.com/newacct/newaccount.asp?cid=3D2682701 This is one of the best payment system in the Internet where your money is backed up by gold. STEP 2: Once you have your egold account running; use egold to post $1 to EACH of the 6 egold accounts below. Find the ways to upload money to your egold account with a credit card or other systems described on the egold site. It's easy and absolutely legal! You are requesting a legitimate service and you are paying for it! Like most of us I was a little skeptical and a little worried about the legal aspects of it all. But I looked around and did some homework and found it was perfectly legal. Here are the 6 individual egold accounts numbers that you have to send $1 to for this to work properly and for you to receive money. (If you don't send the money and decide to post the message with your name in it anyway, you won't earn that much money you could have. If you did this you could get into serious trouble because it is fraud. So follow the instructions and post the $6 and you will make lots of money with no hassles.) Now send $1 to each of these following egold accounts from yours: and pay $1 to each the following 6 egold accounts. In the MEMO box type in Please add me to your mailing list - NOTE: if an egold account on the list is closed, just skip it and go on to the next account in the list. Here is the latest set of emails: 1. 2087908 2. 3197003 3. 3200831 4. 2632950 5. 2682701 6. 4992720 STEP 3: After you sent money to these accounts take the #1 account off the list that you see above, move the other accounts up (6 becomes 5, 5 becomes 4) and add Your account as number 6 on the list. STEP 4: Change anything you need to, but try to keep this article as close to the original as possible. Now, post your amended article to at least 200 newsgroups (there are thousands of groups). And email your message to as many people you can But remember, the more you post and email the more money you make! This is perfectly legal! If you have any doubts, refer to Title 18 Sec. 1302; 1241 of the Postal Lottery laws. Keep a copy of these steps for yourself and, whenever you need money, you can use it again and again. PLEASE REMEMBER: This program remains successful because of the honesty and integrity of the participants and by their carefully adhering to the directions. You are simply paying into a money making chain of participants and if the chain is broken you are taking away from the money making opportunities of someone else. So, as each person who joins the family and the directions are followed, three members will be reimbursed for their participation as a List Developer with one dollar each. You then insert your account into the list and it will move up geometrically. So that when your name reaches the #1 position you will have potentially received thousands of dollars into your account!!! What an opportunity for only a total of $6.00!! $1 for each of the first three people listed above. To begin with, please send you're joining fee now and then add your own account to the list and you're in business! HOW TO POST TO NEWS GROUPS? Use Netscape or Internet Explorer and try searching for various newsgroups (on-line forums, message boards, chat sites, discussions.) Log on any search engine like yahoo.com, google.com, altavista.com, excite.com, etc., then search with the subject "millionaire message board; or; money making message board; or; employment message board; or making discussions; or ''money making forum; or; business message board; etc. You will find thousands & thousands of message boards. Click on them one by one and you will find the option 'post a new message'. Then Post this article as a 'new message' by highlighting the text of this letter and selecting copy then paste from the edit menu. Fill in the Subject, this will be the header that everyone sees as they scroll through the list of postings in a particular group, click the post message button. You're done with your first one! It only takes about 60 seconds to complete postings on message boards after you catch on. REMEMBER, THE MORE NEWSGROUPS YOU POST IN, THE MORE MONEY YOU WILL MAKE!! BUT YOU HAVE TO POST A MINIMUM OF 200! That is it you will begin receiving money in your account from around the world within days! JUST MAKE SURE ALL THE ACCOUNTS ARE CORRECT. Now the WHY part out of 200 postings: Say I receive only 5 replies (a very low example). So then I made $5.00 with my number at #6 on the letter. Each of the 5 persons who just sent me $1.00 make the MINIMUM 200 postings, each with my name at # 5 and only 5 persons respond to each of the original 5, this is an additional $25.00 for me. Now those 24 each make 200 minimum posts with my name at #4 and only 5 replies each. This brings in an additional $125.00. Those 125 persons turn around and post the MINIMUM 200 with my account number at #3 and receive 5 replies each, I will make an additional $625.00. Ok, now here is the FUN part, each of those 625 people post a MINIMUM of 200 letters with my number at #2 and they receive 5 replies each. That just made me $3,125.00!!! Those 3125 persons will all deliver this message to 200 newsgroups with my number at #1 and if still 5 persons per 200 react, I will receive an additional $15,625.00!! With an investment of only $6.00!! A - M - A - Z - I - N - G -!! When your number is no longer on the list, you just take the latest posting in the newsgroups, and send out another $6.00 to egold numbers on the list, putting your account at number 6 again. And start posting again. The thing to remember is that thousands of people all over the world are joining the Internet and reading these articles everyday. JUST LIKE YOU ARE NOW!! So, can you afford $6.00 to see if it really works!! People have said what if the plan is played out and no one sends you the money? So what! What are the chances of that happening when there are tons of new honest users and new honest people who are joining the Internet & newsgroups everyday and are willing to give it a try?? From romano.giannetti at gmail.com Mon Feb 25 12:24:20 2008 From: romano.giannetti at gmail.com (romano.giannetti at gmail.com) Date: Mon, 25 Feb 2008 09:24:20 -0800 (PST) Subject: Embedding a literal "\u" in a unicode raw string. References: Message-ID: On Feb 25, 6:03 pm, "OKB (not okblacke)" wrote: > > I too encountered this problem, in the same situation (making > strings that contain LaTeX commands). One possibility is to separate > out just the bit that has the \u, and use string juxtaposition to attach > it to the others: > > s = ur"a?ado " u"$\\uparrow$" > > It's not ideal, but I think it's easier to read than your solution > #2. > Yes, I think I will do something like that, although... I really do not understand why \x5c is not interpreted in a raw string but \u005c is interpreted in a unicode raw string... is, well, not elegant. Raw should be raw... Thanks anyway From arnodel at googlemail.com Sun Feb 3 04:20:32 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 3 Feb 2008 01:20:32 -0800 (PST) Subject: Does anyone else use this little idiom? References: Message-ID: <3d809532-08e1-4939-a893-ed3808fa44c4@i12g2000prf.googlegroups.com> On Feb 3, 2:03?am, miller.pau... at gmail.com wrote: > Ruby has a neat little convenience when writing loops where you don't > care about the loop index: you just do n.times do { ... some > code ... } where n is an integer representing how many times you want > to execute "some code." > > In Python, the direct translation of this is a for loop. ?When the > index doesn't matter to me, I tend to write it as: > > for _ in xrange (1,n): > ? ?some code [...] If 'some code' is a function (say f) you can write (with repeat from itertools): for action in repeat(f, n): action() I don't know how 'Pythonic' this would be... -- Arnaud From lists at cheimes.de Fri Feb 1 10:45:57 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 01 Feb 2008 16:45:57 +0100 Subject: giving imp.load_module not a real file, HOW? In-Reply-To: <47a2d43c$0$85796$e4fe514c@news.xs4all.nl> References: <47a2d43c$0$85796$e4fe514c@news.xs4all.nl> Message-ID: Paul Sijben wrote: > For some reason imp.load_module insists on getting a real open file as > the second parameter. I have not able to fool it with stringIO or > overloaded file objects. > > So now I have two questions: > 1) why does load_module insist on a real file > 2) is there a way around it that does not involve (say) tempfile? imp.load_module is implemented in C. The API expects a file object or a file descriptor number. Internally the code creates a file pointer *FILE from a file descriptor. You have to create a temporary file. Christian From lists at cheimes.de Sun Feb 10 21:49:07 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 11 Feb 2008 03:49:07 +0100 Subject: Turn off ZeroDivisionError? In-Reply-To: <91db91f2-daef-4e32-b287-b2dadb76fa0f@m34g2000hsb.googlegroups.com> References: <63d2e7d1-aa26-4ddc-9d12-42ae636104c1@s37g2000prg.googlegroups.com> <13qunlu5nrva731@corp.supernews.com> <91db91f2-daef-4e32-b287-b2dadb76fa0f@m34g2000hsb.googlegroups.com> Message-ID: <47AFB7A3.1030707@cheimes.de> Mark Dickinson wrote: > Any suggestions about how to achieve the above-described state of > affairs are welcome! I have worked out a suggestion in three parts. Part 1 ------ The PyFloat C API gets two more functions: int PyFloat_SetIEEE754(int new_state) -> old state int PyFloat_GetIEEE754(void) -> current state By default the state is 0 which means no IEEE 754 return values for 1./0., 0./0. and maybe some other places. An op like 1./0. raises an exception. With state 1 float ops like f/0. returns copysign(INF, f) and for f=0. it returns a NaN. ints and longs aren't affected by the state. The state is to be stored and fetched from Python's thread state object. This could slow down floats a bit because every time f/0. occurs the state has to be looked up in the thread state object. Part 2 ------ The two function are exposed to Python code as math.set_ieee754 and math.get_ieee754. As an alternative the functions could be added to a new module ieee754 or to the float type. Part 3 ------ contextlib gets a new context for ieee754 class ieee754(object): def __init__(self, state=1): self.new_state = state def __enter__(self): self.old_state = math.set_ieee754(self.new_state) def __exit__(self, *args): math.set_ieee754(self.old_state) usage: with contextlib.ieee754(): ... Christian From bbxx789_05ss at yahoo.com Tue Feb 26 05:54:06 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Tue, 26 Feb 2008 02:54:06 -0800 (PST) Subject: network programming: how does s.accept() work? References: <6d564fca-3884-4665-8a86-f7e658217a33@e60g2000hsh.googlegroups.com> <446482ef-1fd8-41dc-a8fd-44de8b51a8e8@o10g2000hsf.googlegroups.com> <379fcee4-15e0-48c2-863b-4b7458893cbe@h25g2000hsf.googlegroups.com> Message-ID: On Feb 25, 10:00?pm, Roy Smith wrote: > In article > , > > ?7stud wrote: > > But your claim that the server doesn't change its port flies in the > > face of every description I've read about TCP connections and > > accept(). ?The articles and books I've read all claim that the server > > port 5053 is a 'listening' port only. ?Thereafter, when a client sends > > a request for a connection to the listening port, the accept() call on > > the server creates a new socket for communication between the client > > and server, and then the server goes back to listening on the original > > socket. > > You're confusing "port" and "socket". > > A port is an external thing. ?It exists in the minds and hearts of packets > on the network, and in the RFCs which define the TCP protocol (UDP too, but > let's keep this simple). > > A socket is an internal thing. ?It is a programming abstraction. ?Sockets > can exist that aren't bound to ports, and several different sockets can be > bound to the same port. ?Just like there can be multiple file descriptors > which are connected to a given file on disk. > > The TCP protocol defines a state machine which determines what packets > should be sent in response when certain kinds of packets get received. ?The > protocol doesn't say how this state machine should be implemented (or even > demands that it be implemented at all). ?It only requires that a TCP host > behave in a way which the state machine defines. > > In reality, whatever operating system you're running on almost certainly > implements in the kernel a state machine as described by TCP. ?That state > machine has two sides. ?On the outside is the network interface, which > receives and transmits packets. ?On the inside is the socket interface to > user-mode applications. ?The socket is just the API by which a user program > interacts with the kernel to get it to do the desired things on the network > interface(s). > > Now, what the articles and books say is that there is a listening SOCKET. ? > And when you accept a connection on that socket (i.e. a TCP three-way > handshake is consummated on the network), the way the socket API deals with > that is to generate a NEW socket (via the accept system call). ?There > really isn't any physical object that either socket represents. ?They're > both just programming abstractions. > > Does that help? If two sockets are bound to the same host and port on the server, how does data sent by the client get routed? Can both sockets recv() the data? From detlev at die-offenbachs.de Sun Feb 3 10:45:52 2008 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sun, 03 Feb 2008 16:45:52 +0100 Subject: ANN: eric4 4.1.0 released Message-ID: Hi, eric4 4.1.0 was just released. This is a major feature release. Compared to 4.0.4 it contains these features next to bug fixes. - Added a plugin system for easy extensibility - Converted the following interface to plugins available separately -- PyLint checker -- CxFreeze packager -- CharTables tool -- CVS version control system -- BRM refactoring - Added new project types -- Eric4 Plugin -- Django -- TurboGears -- wxPython - Added source code exporters for -- HTML -- PDF -- RTF -- Latex - Added subversion repository and log browsers - Included API files for -- eric4 -- Django -- TurboGears -- wxPython -- Zope 2 -- Zope 3 - Many enhancements to the functionality already there What is eric4? -------------- eric4 is a Python (and Ruby) IDE with all batteries included. Please see http://www.die-offenbachs.de/eric for details and screenshots. Regards, Detlev -- Detlev Offenbach detlev at die-offenbachs.de From gaohawk at gmail.com Fri Feb 29 05:02:06 2008 From: gaohawk at gmail.com (hawk gao) Date: Fri, 29 Feb 2008 18:02:06 +0800 Subject: A python STUN client is ready on Google Code. Message-ID: <8ce119530802290202y67e89f21mee919f8c4d2aa99@mail.gmail.com> http://code.google.com/p/boogu/ Enjoy it! Hawk From bj_666 at gmx.net Thu Feb 28 02:37:46 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 28 Feb 2008 07:37:46 GMT Subject: How about adding rational fraction to Python? References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <7x63wbez2b.fsf@ruckus.brouhaha.com> <13sc3ccds5ap5a9@corp.supernews.com> <7x1w6xrfxe.fsf@ruckus.brouhaha.com> <13sc86hjaabtu9c@corp.supernews.com> <7xy795n5to.fsf@ruckus.brouhaha.com> Message-ID: <62n6maF23jpgaU3@mid.uni-berlin.de> On Wed, 27 Feb 2008 19:00:19 -0800, Paul Rubin wrote: > Steven D'Aprano writes: >> Okay, that's just insane, making distinctions between literals and >> variables like that. >> >> 1 + 1.0 # okay > > => Yes > >> x = 1 >> x + 1.0 # is this okay or not? who knows? > > => Yes, ok > >> len('s') + 1.0 # forbidden > > Yes, forbidden. > > More examples: > > x = 1 > y = len(s) + x > > => ok, decides that x is an int > > x = 1 > y = x + 3.0 > > => ok, decides that x is a float > > x = 1 > y = x + 3.0 > z = len(s) + x > > => forbidden, x cannot be an int and float at the same time. > >> I am so glad you're not the designer of Python. > > This is how Haskell works and I don't notice much complaints about it. Complain! :-) For implementing this in Python you have to carry an "is allowed to be coerced to float" flag with every integer object to decide at run time if it is an error to add it to a float or not. Or you make Python into a statically typed language like Haskell. But then it's not Python anymore IMHO. Ciao, Marc 'BlackJack' Rintsch From exarkun at divmod.com Mon Feb 11 10:03:46 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 11 Feb 2008 10:03:46 -0500 Subject: use 'with' to redirect stdout In-Reply-To: Message-ID: <20080211150346.6859.510299158.divmod.quotient.8039@ohm> On Mon, 11 Feb 2008 09:38:34 -0500, Neal Becker wrote: >Jean-Paul Calderone wrote: > >> On Mon, 11 Feb 2008 09:15:07 -0500, Neal Becker >> wrote: >>>Is there a simple way to use a 'with' statement to redirect stdout in a >>>block? >> >> Do you mean "without writing a context manager to do the redirection"? >> > >I mean, whatever is the simplest solution. I don't know much about the >subject of context manager at this point. > Something like http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/534166 will probably do what you want. Jean-Paul From bronger at physik.rwth-aachen.de Sun Feb 3 12:10:30 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sun, 03 Feb 2008 18:10:30 +0100 Subject: Python GUI toolkit References: <87ejbuoxed.fsf@physik.rwth-aachen.de> <13qbsgfauejb8cc@corp.supernews.com> Message-ID: <87abmiotix.fsf@physik.rwth-aachen.de> Hall?chen! Grant Edwards writes: > On 2008-02-03, Torsten Bronger wrote: >> Hall?chen! >> >> default at defaulted.default writes: >> >>> [...] >>> >>> the only remaining are qt4 and wx, i would like to know if one >>> of these or any other toolkit is capable of creating >>> good-looking GUI's, like in other apps, for e.g, .net apps. >> >> I think both Qt4 and wx create good-looking GUIs, since Qt4 now >> tries to use the widgets from the platform it's running on. > > Really? Qt uses GTK when running uder Gnome or XFCE?? I said "try". You won't find a toolkit which mimics every desktop environment. However, Qt used to ignore the current look-and-feel deliberately. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From darcy at druid.net Wed Feb 27 17:49:29 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 27 Feb 2008 17:49:29 -0500 Subject: Making string-formatting smarter by handling generators? In-Reply-To: References: <47C58E95.1030000@tim.thechases.com> Message-ID: <20080227174929.be058819.darcy@druid.net> On Wed, 27 Feb 2008 13:06:27 -0800 (PST) Arnaud Delobelle wrote: > On Feb 27, 5:25?pm, "D'Arcy J.M. Cain" wrote: > > Isn't map() deprecated? ?The above can be done with; > I don't think that map() is deprecated. In python 3.0 it is still > present, only it returns an iterator instead of a list. Discouraged then? Our benign dictator has said that filter and map must die. Others suggest that map is not as efficient. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From Graham.Dumpleton at gmail.com Sun Feb 3 00:32:29 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Sat, 2 Feb 2008 21:32:29 -0800 (PST) Subject: Multiple interpreters retaining huge amounts of memory References: <47a3c88c$0$8380$9b622d9e@news.freenet.de> Message-ID: <720a3e4f-ca24-4d22-be66-e00bcac5621a@d21g2000prf.googlegroups.com> On Feb 2, 12:34?pm, "Martin v. L?wis" wrote: > > Is there some way to track references per interpreter, or to get the > > memory allocator to set up seperate arenas per interpreter so that it > > can remove all allocated memory when the interpreter exits? > > No. The multi-interpreter feature doesn't really work, so you are > basically on your own. If you find out what the problem is, please > submit patches to bugs.python.org. > > In any case, the strategy you propose (with multiple arenas) would *not* > work, since some objects have to be shared across interpreters. > > Regards, > Martin The multi interpreter feature has some limitations, but if you know what you are doing and your application can be run within those limitations then it works fine. If you are going to make a comment such as 'multi-interpreter feature doesn't really work' you really should substantiate it by pointing to where it is documented what the problems are or enumerate yourself exactly what the issues are. There is already enough FUD being spread around about the ability to run multiple sub interpreters in an embedded Python application, so adding more doesn't help. Oh, it would also be nice to know exactly what embedded systems you have developed which make use of multiple sub interpreters so we can gauge with what standing you have to make such a comment. Graham From castironpi at gmail.com Tue Feb 19 15:49:03 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 19 Feb 2008 12:49:03 -0800 (PST) Subject: The big shots References: <89d15587-e8de-444c-b240-4a10305146e0@e23g2000prf.googlegroups.com> <61vkf0F20u2k9U1@mid.uni-berlin.de> <47baba55$0$20775$426a74cc@news.free.fr> Message-ID: <16aa4c9e-a63a-4066-9aeb-b2832856c82e@q70g2000hsb.googlegroups.com> On Feb 19, 5:17?am, Bruno Desthuilliers wrote: > Diez B. Roggisch a ?crit :> castiro... at gmail.com schrieb: > >> I'm a little dissatisfied, and just thinking aloud. > > (snip remaining of mostly inarticulate post, just couldn't make sens of > it - as usual) > > > No idea what's wrong with these people here - but I bet if you team up > > with Illias, you can start working on his language-to-rule-them-all in > > no time, shortening the delivery goal of 2011 immensly. > > Hum... Perhaps a bit harsh, but there's something here : castironpi's > posts definitively have something in common with Illias' ones. Couldn't > name exactly what, but still... > > > If you really hope to get any serious attention, stop whining and learn > to express yourself clearly. This won't necessarily make anybody agree > with your proposals, but at least chances are someone will read them. > Ok, take this one. C is faster than Python. It would be useful, in certain cases, to write C. It is possible but inconvenient, out of the way. Date: Sat, 9 Feb 2008 11:48:51 -0800 (PST) Subject: C function in a Python context http://groups.google.com/group/comp.lang.python/browse_frm/thread/cd2f79dd12e81912/ A simple compile and link function. Useful for basic cases; if you want to get fancy, don't use it. My suspicion is that my choices of message subjects, function names, and variable names, is the biggest hang up. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Feb 15 03:45:10 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 15 Feb 2008 09:45:10 +0100 Subject: adding values to keys In-Reply-To: <13rajnrjk9toicd@corp.supernews.com> References: <34005f69-4031-4baf-8014-d209e818ec85@s19g2000prg.googlegroups.com> <13rajnrjk9toicd@corp.supernews.com> Message-ID: <47b550d5$0$22224$426a74cc@news.free.fr> Dennis Lee Bieber a ?crit : > On Thu, 14 Feb 2008 23:55:21 -0800 (PST), Brandon > declaimed the following in comp.lang.python: (snip) >> MT.fromkeys(NT[0], range(alpha,omega)) > > Note that NT is a single tuple -- your previous loop throws away the > prior value and binds a new tuple each time. AND IT IS A TUPLE = ('z', > [0, 1, 2, 3]), NT[0] is just "z" -- it does not have "keys" to use in > the "fromkeys()" method. Note that the first arg to dict.fromkeys doesn't need to have a .keys method - you can pass in any iterable, and even a single hashable (in which case your ditc will only have one key, of course). >>> dict.fromkeys('abc') {'a': None, 'c': None, 'b': None} >>> dict.fromkeys(c for c in 'abc') {'a': None, 'c': None, 'b': None} >>> dict.fromkeys((1,2,3)) {1: None, 2: None, 3: None} >>> dict.fromkeys('a') {'a': None} From jeff at schwabcenter.com Tue Feb 26 17:17:50 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Tue, 26 Feb 2008 14:17:50 -0800 Subject: Adobe CS3 In-Reply-To: References: <15662975.post@talk.nabble.com> <47c471ac$0$26058$88260bb3@free.teranews.com> Message-ID: D'Arcy J.M. Cain wrote: > On Tue, 26 Feb 2008 12:58:53 -0800 > Tobiah wrote: >>> A: Because it messes up the order in which people normally read text. >>> Q: Why is top-posting such a bad thing? >> But then again, when just adding a quip to a long thread in which >> the readers have already seen the previous comments, top posting >> can be an advantage to the reader. > > Unless, of course, you know how to trim quoted text. And unless the reader (like me) tends to scroll immediately to the bottom of the post anyway, without looking for a one-line comment at the top. From jeff at schwabcenter.com Wed Feb 13 12:48:56 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Wed, 13 Feb 2008 09:48:56 -0800 Subject: Python equivt of __FILE__ and __LINE__ In-Reply-To: References: <1pudnQHrDeRBhi3anZ2dnUVZ8uudnZ2d@bt.com> <3877fea5-b67d-4e82-9dfd-a49accddbd4a@d21g2000prf.googlegroups.com> Message-ID: alain wrote: > On Feb 12, 7:44 pm, Jeff Schwab wrote: > >> It still would be nice to have syntax as clean as __FILE__ and __LINE__. > > There exists an undocumented builtin called __file__, but > unfortunately no corresponding __line__ Drat! So close! Thanks for the info. Oh well, I guess special cases aren't all that special, anyway. Maybe a function called srcinfo.here() could return a tuple of the file name and line number, to allow syntax like: print("The program has reached %f:%d" % srcinfo.here()) Methods names like file_name() and line_no() aren't too hideous, either. From bearophileHUGS at lycos.com Mon Feb 25 18:16:18 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 25 Feb 2008 15:16:18 -0800 (PST) Subject: PyEuler References: <9e435ab2-3323-4ad9-9dd9-cdde34c3fb91@e25g2000prg.googlegroups.com> <7x1w70x2hd.fsf@ruckus.brouhaha.com> <0a552b42-69f0-492f-9357-38ad5226c4ed@d4g2000prg.googlegroups.com> <763fca3a-d863-4d37-b485-4845686d825a@62g2000hsn.googlegroups.com> Message-ID: Arnaud Delobelle: > I disagree; the generator function has no right to keep a and b to > itself. a and b cry out to be function parameters. I see. Then that's a generator for a generalized Fibonacci sequence :-) Your version too is useful. Bye, bearophile From steve at REMOVE-THIS-cybersource.com.au Mon Feb 25 10:02:38 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 25 Feb 2008 15:02:38 -0000 Subject: How about adding rational fraction to Python? References: <649ac8a9-ae09-4e9b-85c2-f37043af21fd@28g2000hsw.googlegroups.com> <0d1955fc-762c-44e1-a5d8-372c71458455@p25g2000hsf.googlegroups.com> <36204e6f-0d82-449b-8ca5-c819ace9a55a@p73g2000hsd.googlegroups.com> <7xy799v7o1.fsf@ruckus.brouhaha.com> <13s4s9s3khlom61@corp.supernews.com> Message-ID: <13s5m4eap0a567a@corp.supernews.com> On Sun, 24 Feb 2008 23:41:53 -0800, Dennis Lee Bieber wrote: > On 24 Feb 2008 23:04:14 -0800, Paul Rubin > declaimed the following in comp.lang.python: > > >> Usually you would round to the nearest penny before storing in the >> database. > > Tell that to the payroll processing at Lockheed...My paycheck > tends to vary from week to week as the database apparently carries > amount to at least 0.001 resolution, only rounding when distributing > among various taxes for the paycheck itself. Tedious data entry in > Quicken as I have to keep tweaking various tax entries by +/- a penny > each week. "Worst practice" in action *wink* I predict they're using some funky in-house accounting software they've paid millions to a consultancy firm (SAP?) for over the decades, written by some guys who knows lots of Cobol but no accounting, and the internal data type is a float. [snip] > Oh... And M$ -- the currency type in VB is four decimal places. Accounting standards do vary according to context: e.g. I see that offical Australian government reporting standards for banks is to report in millions of dollars rounded to one decimal place. Accountants can calculate things more or less any way they like, so long as they tell you. I found one really dodgy example: "The MFS Water Fund ARSN 123 123 642 (?the Fund?) is a registered managed investment scheme. ... MFS Aqua may calculate the Issue Price to the number of decimal places it determines." Sounds like another place using native floats. But it's all above board, because they tell you they'll use an arbitrary number of decimal places, all the better to confuse the auditors my dear. -- Steven From rupert.thurner at gmail.com Sun Feb 10 17:23:14 2008 From: rupert.thurner at gmail.com (rupert.thurner) Date: Sun, 10 Feb 2008 14:23:14 -0800 (PST) Subject: python 3.0 memory leaking? References: Message-ID: On Feb 10, 9:08?pm, Christian Heimes wrote: > rupert.thurner wrote: > > does python-3.0 improve something to avoid writing memory leaking > > applications? > > No, it doesn't. Python 3.0 and maybe 2.6 are going to have some small > improvements but the improvements aren't related to memory leaking. I'm > working on the matter for a while now. I've limited some free lists and > I've a patch that gives allocated memory back to the OS earlier. > > Have you followed my advice and checked all places that deal with > frames, tracebacks, exception objects and __del__ methods? > > Christian many thanks christian! do you have any code examples how to handle frames, tracebacks, exception objects and __del__ correctly? btw, i put your hints on http://wiki.python.org/moin/FreeMemory. rupert. From jeff at schwabcenter.com Wed Feb 27 22:18:27 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Wed, 27 Feb 2008 19:18:27 -0800 Subject: Pythons & Ladders In-Reply-To: <75969097-e687-4092-af0d-fd6ce4df2f87@28g2000hsw.googlegroups.com> References: <75969097-e687-4092-af0d-fd6ce4df2f87@28g2000hsw.googlegroups.com> Message-ID: <3pidnRLtmJ1KulvanZ2dnUVZ_uyinZ2d@comcast.com> Benoit wrote: > I've been teaching myself the python language over the past few months > using Mark Lutz' Learning Python, 3ed. Python is also the first > programming language I've ever taken up. I find the language easy to > learn and rather productive in relation to the introductory course on C > ++ I'd begun in January for fun @ school (we're practicing dynamic > arrays using pointers... kill me now). Get a better teacher, if you can. Please do me a personal favor: Don't hold the crappy course against C++. For the record, you should never have to manage dynamically allocated arrays manually, nor store pointers to them. Try the std::vector template, and post in comp.lang.c++ if have any trouble. > My problem, however, is that I > found myself lacking problems with which to create solutions and so > practice what I've learned. I think I'm one of those people who > really get into something when the instructions come from without. > > So I'd like to ask you resident python gurus to help me learn. Give > me something to do! Specifically, I'd like to be given tasks that > incrementally increase in difficulty, starting from simple file/text > manipulation to those harder things like built-in function overloading > (you know, where you can make the "+" operator do something different > in relation to a given object). I hope my request doesn't come off as > demanding, as perhaps we could archive these tasks for future > pedagogy. > > If something like this already exists though, please point me in the > right direction. Otherwise, thanks for any and all assistance. Happy hacking! http://www.pythonchallenge.com/ From Jayson.Barley at webtrends.com Thu Feb 21 16:49:02 2008 From: Jayson.Barley at webtrends.com (Jayson Barley) Date: Thu, 21 Feb 2008 21:49:02 -0000 Subject: Inserting NULL values with pymssql In-Reply-To: <3F533E9AEFD4D343B5EA0E475321F21E03196D36@PDXEX01.webtrends.corp> Message-ID: <3F533E9AEFD4D343B5EA0E475321F21E03196D37@PDXEX01.webtrends.corp> I also forgot to mention that this... import pymssql TestDB = pymssql.connect(host='Test',user='test',password='test',database='test') cursor = TestDB.cursor() query = """INSERT INTO test.dbo.test (test) VALUES ('%s');""" cursor.execute(query,(None)) works. While import pymssql TestDB = pymssql.connect(host='Test',user='test',password='test',database='test') cursor = TestDB.cursor() query = """INSERT INTO test.dbo.test (inttest) VALUES ('%d');""" cursor.execute(query,(None)) doesn't work and returns Traceback (most recent call last): File "C:\Test\db_info\test.py", line 6, in cursor.execute(query,(None)) File "C:\Python25\lib\site-packages\pymssql.py", line 126, in execute self.executemany(operation, (params,)) File "C:\Python25\lib\site-packages\pymssql.py", line 152, in executemany raise DatabaseError, "internal error: %s" % self.__source.errmsg() pymssql.DatabaseError: internal error: SQL Server message 245, severity 16, state 1, line 1: Conversion failed when converting the varchar value '%d' to data type int. DB-Lib error message 10007, severity 5: General SQL Server error: Check messages from the SQL Server. Jayson ________________________________ From: python-list-bounces+jayson.barley=webtrends.com at python.org [mailto:python-list-bounces+jayson.barley=webtrends.com at python.org] On Behalf Of Jayson Barley Sent: Thursday, February 21, 2008 1:20 PM To: python-list at python.org Subject: Inserting NULL values with pymssql I am attempting to insert NULL values into a database. I have tried to do this in multiple ways without any success, see below, and haven't been able to find anything through Google to help out. I am hoping that I am just overlooking something or that it is a rookie mistake. Below is a test I came up with to prove this. I am on Windows XP using Python 2.5 and pymssql-0.8.0-py2.5. CREATE TABLE [dbo].[Test]( [test] [varchar](50) NULL, [inttest] [int] NULL ) ON [PRIMARY] 1. import pymssql TestDB = pymssql.connect(host='Test',user='test',password='test',database='test') cursor = TestDB.cursor() query = """INSERT INTO test.dbo.test VALUES (?, ?);""" cursor.execute(query,('','')) Returns Traceback (most recent call last): File "C:\Test\db_info\test.py", line 6, in cursor.execute(query,('','')) File "C:\Python25\lib\site-packages\pymssql.py", line 126, in execute self.executemany(operation, (params,)) File "C:\Python25\lib\site-packages\pymssql.py", line 152, in executemany raise DatabaseError, "internal error: %s" % self.__source.errmsg() pymssql.DatabaseError: internal error: None 2. import pymssql TestDB = pymssql.connect(host='Test',user='test',password='test',database='test') cursor = TestDB.cursor() query = """INSERT INTO test.dbo.test VALUES (?, ?);""" cursor.execute(query,('',None)) Returns Traceback (most recent call last): File "C:\Test\db_info\test.py", line 8, in cursor.execute(query,('',None)) File "C:\Python25\lib\site-packages\pymssql.py", line 126, in execute self.executemany(operation, (params,)) File "C:\Python25\lib\site-packages\pymssql.py", line 152, in executemany raise DatabaseError, "internal error: %s" % self.__source.errmsg() pymssql.DatabaseError: internal error: None 3. import pymssql TestDB = pymssql.connect(host='Test',user='test',password='test',database='test') cursor = TestDB.cursor() query = """INSERT INTO test.dbo.test VALUES (?, ?);""" cursor.execute(query,('','NULL')) Returns Traceback (most recent call last): File "C:\Test\db_info\test.py", line 6, in cursor.execute(query,('','NULL')) File "C:\Python25\lib\site-packages\pymssql.py", line 126, in execute self.executemany(operation, (params,)) File "C:\Python25\lib\site-packages\pymssql.py", line 152, in executemany raise DatabaseError, "internal error: %s" % self.__source.errmsg() pymssql.DatabaseError: internal error: None I am wondering what I am missing that is preventing me from inserting a NULL. I can perform the INSERT in Server Management Studio the problem only exists in the Python script. If anyone can point me to a resource that I may have missed or a flaw in my script I would really appreciate it. Jayson -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr.com Fri Feb 22 16:50:53 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 22 Feb 2008 13:50:53 -0800 (PST) Subject: Simple - looking for a way to do an element exists check.. References: <7x8x1c25cz.fsf@ruckus.brouhaha.com> <7x3ark2560.fsf@ruckus.brouhaha.com> <7xwsowd64j.fsf@ruckus.brouhaha.com> Message-ID: <48929a21-76dc-486d-bf5e-4e028743ad02@f47g2000hsd.googlegroups.com> On Feb 22, 3:38?pm, Paul Rubin wrote: > Paul McGuire writes: > > I think you have this backwards. ?Should be: > > > ? ? ?if not any(x[0]==element[0] for x in a): > > ? ? ? ? a.append(element) > > I think you are right, it was too early for me to be reading code when > I posted that ;-) I'm still getting used to 'any' and 'all' as new Python built-ins - but they'll do the short-circuiting as well as a for-loop-with-break. But I think a set- or dict-based solution will still surpass a list- based one for the OP. -- Paul From http Wed Feb 27 21:43:24 2008 From: http (Paul Rubin) Date: 27 Feb 2008 18:43:24 -0800 Subject: How about adding rational fraction to Python? References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <13sc195m4d3qbda@corp.supernews.com> <7x8x1551nq.fsf@ruckus.brouhaha.com> <13sc79jk28hfrf1@corp.supernews.com> Message-ID: <7x7igpn6lv.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > def pmean(data): # Paul Rubin's mean > """Returns the arithmetic mean of data, unless data is all > ints, in which case returns the mean rounded to the nearest > integer less than the arithmetic mean.""" > s = sum(data) > if isinstance(s, int): return s//len(data) > else: return s/len(data) Scheme and Common Lisp do automatic conversion and they thought out the semantics rather carefully, and I think both of them return exact rationals in this situation (int/int division). I agree with you that using // as above is pretty weird and it may be preferable to raise TypeError on any use of int/int (require either an explicit conversion, or use of //). From mnordhoff at mattnordhoff.com Mon Feb 11 23:23:05 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Tue, 12 Feb 2008 04:23:05 +0000 Subject: Is there a web visitor counter available in Python ... In-Reply-To: References: Message-ID: <47B11F29.5020306@mattnordhoff.com> W. Watson wrote: > ... that is free for use without advertising that I can use on my web pages? > I have no idea is suitable for this. My knowledge of Python is somewhat > minimal at this point. Maybe Java is better choice. You can analyze your web logs. That's more accurate than a hit counter, though you can't use it for bragging rights. -- From magdoll at gmail.com Sat Feb 9 16:51:34 2008 From: magdoll at gmail.com (Magdoll) Date: Sat, 9 Feb 2008 13:51:34 -0800 (PST) Subject: different key, same value in dictionaries Message-ID: Is there a cleaner way to do this example: d = {('a','b'): 10, ('a','c'): 20, ('b','c'): 30} The key is always a pair (x,y), but d[(x,y)] should have the same result as d[(y,x)]. So either I would have to store both d[(x,y)] and d[(y,x)] (unncessary extra space?), or write something like: if x <= y: return d[(x,y)] else: return d[(y,x)] I'm not familiar with python enough, so I want to know whether these are my only choices.... From byte8bits at gmail.com Wed Feb 13 15:19:15 2008 From: byte8bits at gmail.com (brad) Date: Wed, 13 Feb 2008 15:19:15 -0500 Subject: Email Directly from python Message-ID: I'd like to send email directly from within python without having to rely on an external smtp server. You know, something like the good, old Unix... echo My_message | mail -s Subject person at someplace.com Can Python do something similar in a portable fashion without a smtp server installed on the machine? Thanks, Brad From tenax.raccoon at gmail.com Tue Feb 19 09:37:13 2008 From: tenax.raccoon at gmail.com (Jason) Date: Tue, 19 Feb 2008 06:37:13 -0800 (PST) Subject: Double underscores -- ugly? References: Message-ID: <8cee096e-7f27-4162-ae09-e0fdbbc91db6@s8g2000prg.googlegroups.com> On Feb 18, 3:28 pm, benhoyt wrote: > Hi guys, > > I've been using Python for some time now, and am very impressed with > its lack of red tape and its clean syntax -- both probably due to the > BDFL's ability to know when to say "no". > > Most of the things that "got me" initially have been addressed in > recent versions of Python, or are being addressed in Python 3000. But > it looks like the double underscores are staying as is. This is > probably a good thing unless there are better alternatives, but ... > > Is it just me that thinks "__init__" is rather ugly? Not to mention > "if __name__ == '__main__': ..."? > > I realise that double underscores make the language conceptually > cleaner in many ways (because fancy syntax and operator overloading > are just handled by methods), but they don't *look* nice. > > A solution could be as simple as syntactic sugar that converted to > double underscores behind the scenes. A couple of ideas that come to > my mind (though these have their problems too): > > def ~init(self): # shows it's special, but too like a C++ destructor > def +init(self): # a bit too additive :-) > defop add(self, other): # or this, equivalent to "def __add__" > def operator add(self, other): # new keyword, and a bit wordy > > Has anyone thought about alternatives? Is there a previous discussion > on this I can look up? > > Cheers, > Ben. Hmm. I must be the only person who doesn't think the double underscores are ugly. To me, they seem to provide plenty of attention to the special methods, but still appear clean due to their almost white-space-like nature. Given the use of underscores to indicate italics in plain-text, the special methods seem (to me) to have extra emphasis. I don't print my code often, so that's a caveat, and I came from a C/C+ + background. I agree with Ben, that your suggestions don't particularly stand out. They might stand out if the editor you used supported syntax highlighting. Personally, I find the examples with the plus and tilde (+, ~) to be more noisy and ugly than the underscores. Think of the underscores as a serene white-space day, with a simple black road that takes you to the special name. Or, you can wonder what I'm smoking when I code.... *grin* --Jason From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Feb 14 08:26:01 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 14 Feb 2008 14:26:01 +0100 Subject: Floating point bug? In-Reply-To: References: <13r7vf26q9qns8b@corp.supernews.com> Message-ID: <47b4412c$0$10887$426a74cc@news.free.fr> Christian Heimes a ?crit : > Dennis Lee Bieber wrote: >> What's wrong with just >> >> str(0.3) >> >> that's what "print" invokes, whereas the interpreter prompt is using >> >> repr(0.3) >> > > No, print invokes the tp_print slot of the float type. Some core types > have a special handler for print. The tp_print slot is not available > from Python code and most people don't know about it. :] ??? bruno at bruno:~$ python Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class Toto(object): ... def tp_print(self): ... return "AHAHAHA" ... >>> t = Toto() >>> t <__main__.Toto object at 0xb7db8d6c> >>> print t <__main__.Toto object at 0xb7db8d6c> >>> (0.3).tp_print Traceback (most recent call last): File "", line 1, in AttributeError: 'float' object has no attribute 'tp_print' >>> (0.3).__print__ Traceback (most recent call last): File "", line 1, in AttributeError: 'float' object has no attribute '__print__' >>> (0.3).__tp_print__ Traceback (most recent call last): File "", line 1, in AttributeError: 'float' object has no attribute '__tp_print__' >>> I Must have miss something... From dotancohen at gmail.com Sat Feb 2 07:10:09 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Sat, 2 Feb 2008 14:10:09 +0200 Subject: Why the HELL has nobody answered my question !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! In-Reply-To: <47A12FE9.3020209@ncee.net> References: <27CC3060AF71DA40A5DC85F7D5B70F380239F23C@AWMAIL04.belcan.com> <47A11E78.7030003@tim.thechases.com> <47A12FE9.3020209@ncee.net> Message-ID: <880dece00802020410q737a48dcn2dc86c5b91b46d42@mail.gmail.com> On 31/01/2008, Shane Geiger wrote: > The answer is here: > http://www.google.com/search?q=gene+expression+programming+python > Not anymore. Now, that page is all links to this thread! Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From bignose+hates-spam at benfinney.id.au Mon Feb 4 02:32:07 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 04 Feb 2008 18:32:07 +1100 Subject: type, object hierarchy? References: <814a05b4-6f13-4c86-8c68-a30da06ca093@b2g2000hsg.googlegroups.com> <2ba95819-0699-49c6-b7e9-96d54763be52@v17g2000hsa.googlegroups.com> <4a2fabf4-5a4d-4afc-a722-f2887da10d1f@q39g2000hsf.googlegroups.com> Message-ID: <87ir15dvns.fsf@benfinney.id.au> Robert Kern writes: > And if you want to really blow your mind, > > print isinstance(type, object) # True > print isinstance(object, type) # True Not what I see here. Python 2.4.4 (#2, Jan 3 2008, 13:39:07) [GCC 4.2.3 20071123 (prerelease) (Debian 4.2.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> issubclass(type, object) True >>> issubclass(object, type) False Python 2.5.2a0 (r251:54863, Jan 3 2008, 19:40:30) [GCC 4.2.3 20071123 (prerelease) (Debian 4.2.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> issubclass(type, object) True >>> issubclass(object, type) False -- \ "Ignorance more frequently begets confidence than does | `\ knowledge." ?Charles Darwin | _o__) | Ben Finney From msj at infoserv.dk Mon Feb 4 14:50:00 2008 From: msj at infoserv.dk (msj at infoserv.dk) Date: Mon, 4 Feb 2008 11:50:00 -0800 (PST) Subject: Windows - remote system window text References: <3b29a22b-55cd-4430-9a47-cba4941e9b8c@h11g2000prf.googlegroups.com> <9d71dbbb-240a-44c5-9e3f-ef223133152e@z17g2000hsg.googlegroups.com> <11db701c-d1f2-4970-8f83-df214bdca7c5@b2g2000hsg.googlegroups.com> Message-ID: <51c348bd-1aa3-4cad-82e1-42717ccfa08d@q39g2000hsf.googlegroups.com> I can understand that. But look at the bright side, you don't have to rely on windows authentication, you just need an open port. Now i don't know what you are building, but with a client/server setup you can also get to other data that you might need, like mouse movement to detect for activity, username, etc. From steve at holdenweb.com Sat Feb 23 20:44:53 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 23 Feb 2008 20:44:53 -0500 Subject: can't set attributes of built-in/extension type In-Reply-To: References: Message-ID: <47C0CC15.8010105@holdenweb.com> Steve Holden wrote: > Neal Becker wrote: >> Steve Holden wrote: >> >>> Neal Becker wrote: >>>> Steve Holden wrote: >>>> >>>>> Neal Becker wrote: >>>>>> 7stud wrote: >>>>>> >>>>>>> On Feb 21, 11:19 am, Neal Becker wrote: >>>>>>>> I'm working on a simple extension. Following the classic 'noddy' >>>>>>>> example. >>>>>>>> >>>>>>>> In [15]: cmplx_int32 >>>>>>>> Out[15]: >>>>>>>> >>>>>>>> Now I want to add an attribute to this type. More precisely, I want >>>>>>>> a class attribute. >>>>>>>> >>>>>>>> cmplx_int32.test = 0 >>>>>>>> --------------------------------------------------------------------------- >>>>>>>> TypeError Traceback (most recent call >>>>>>>> last) >>>>>>>> >>>>>>>> /home/nbecker/numpy/ in () >>>>>>>> >>>>>>>> TypeError: can't set attributes of built-in/extension >>>>>>>> type 'numpy.cmplx_int32' >>>>>>>> >>>>>>>> What am I missing? >>>>>>> class Dog(object): >>>>>>> def __setattr__(self, attr, val): >>>>>>> print "TypeError: can't set attributes of built-in/extension" >>>>>>> print "type 'Dog.cmplx_int32'" >>>>>>> >>>>>>> d = Dog() >>>>>>> d.test = 0 >>>>>>> >>>>>>> --output:-- >>>>>>> TypeError: can't set attributes of built-in/extension >>>>>>> type 'Dog.cmplx_int32' >>>>>> Not quite, I'm setting a class attribute, not an attribute on an >>>>>> instance. >>>>>> >>>>> Quite. The problem is that extension types' attributes are determined by >>>>> the layout of the object's slots and forever fixed in the C code that >>>>> implements them: the slots can't be extended, so there's no way to add >>>>> attributes. This is an efficiency feature: it would be *extremely* slow >>>>> to look up the basic types' attributes using late-binding (it would also >>>>> change the nature of the language somewhat, making it more like Ruby or >>>>> Self). >>>>> >>>>> So the reason you can't do what you want to is the same reason why you >>>>> can't add attribute to the built-in types (which are, of course, clearly >>>>> mentioned in the error message). >>>>> >>>>> >>> object.anyoldname = "You lose!" >>>>> Traceback (most recent call last): >>>>> File "", line 1, in >>>>> TypeError: can't set attributes of built-in/extension type 'object' >>>>> >>> >>>>> >>>>> If you look in typeobject.c you'll find this error message occurs when >>>>> the object's type isn't a PyHeapTypeObject (in other words, if it's one >>>>> of the built-in or extension types). >>>>> >>>> Thanks, but I'm a bit confused. After reading in my "Python in a >>>> Nutshell", I found that if after calling PyReady on my type object, if I >>>> use PyDict_SetItemString (my_type_obj.tp_dict,) >>>> >>>> That seems to work fine (which isn't exactly what it said in the Nutshell >>>> book, but close). >>>> >> I wanted to add an attribute to my type. >> Specifically, my type object is a static cmplx_int32_scalar_obj. >> >> After calling PyType_Ready (&cmplx_int32_scalar_obj), then I did >> PyDict_SetItemString (cmplx_int32_scalar_obj.tp_dict, "dtype", (PyObject*)d1); >> >> Now my type has the property: >> cmplx_int32.dtype >> dtype('cmplx_int32') >> >> Now, I do see that I still can't set it: >> >> cmplx_int32.dtype = 2 >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: can't set attributes of built-in/extension type 'numpy.cmplx_int32' >> >> In this case, I don't need to. >> >> But I still don't know why I can have a python class and set class or instance >> attributes as I like, but this type acts differently. What would I need to >> do if I did want to allow arbitrary attributes to be set/added to my type? >> > I believe it's because PyType_Ready(), among its many other duties, > calls mro_internal() on the type. It seems obvious that one would want > to optimize the MRO by not allowing modifications. Yet in C it is > possible, as you point out, to do so. Hmm ... > > I'll let you know if I come to any conclusion - a query to python-dev > would probably get an answer, but surely someone on this list knows already? > > [Left this as a draft for a while to mull it over]. > > After further consideration I have concluded (without further scrutiny > of the source) that it's because the method slots in C-implemented types > are pointers to C functions not to Python functions. Would this make sense? > Just to close this one off, Neal wrote to python-dev and got the following reply from Guido himself. > On Sat, Feb 23, 2008 at 4:55 PM, Neal Becker wrote: >> There is some discussion on this subject, archived here: >> http://permalink.gmane.org/gmane.comp.python.general/560661 >> >> I wonder if anyone could shed some light on this subject? >> >> (Or, help me understand, what is the difference between a type that I create >> using python C api and a python class?) > > This is prohibited intentionally to prevent accidental fatal changes > to built-in types (fatal to parts of the code that you never though > of). Also, it is done to prevent the changes to affect different > interpreters residing in the address space, since built-in types > (unlike user-defined classes) are shared between all such > interpreters. > > -- > --Guido van Rossum (home page: http://www.python.org/~guido/) regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From bignose+hates-spam at benfinney.id.au Thu Feb 14 19:13:53 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 15 Feb 2008 11:13:53 +1100 Subject: XML pickle References: <686a4012-1c9e-456e-973c-c1e396f4c060@s8g2000prg.googlegroups.com> <47B3E3A3.1070205@behnel.de> <47B488FD.1090502@behnel.de> <47B49B3E.3060609@behnel.de> <37a7ec38-d210-490f-b2eb-5db6f6ac6732@e10g2000prf.googlegroups.com> Message-ID: <878x1n13ge.fsf@benfinney.id.au> castironpi at gmail.com writes: > Minimize redundancy. Please do so by trimming the quoted material; remove anything not relevant to people reading your reply. -- \ "I moved into an all-electric house. I forgot and left the | `\ porch light on all day. When I got home the front door wouldn't | _o__) open." -- Steven Wright | Ben Finney From martin at v.loewis.de Fri Feb 1 15:12:38 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 01 Feb 2008 21:12:38 +0100 Subject: Why the HELL has nobody answered my question !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! In-Reply-To: References: <47a2bcb3$0$5952$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <47A37D36.4000702@v.loewis.de> > Seems like they'd have trouble with cooling problems... > (okay, I was just told yesterday that "hell is hot" is a > culturally relative thing, and that the Nordic version of hell > involves extreme cold. ymmv) That depends on the rate at which hell is expanding. If it is expanding at a slower rate than souls entering, it is exothermic and pressure will increase until all hell breaks loose. If it is expanding at a higher rate, it is endothermic, and temperature will drop until hell freezes over. See http://www.pinetree.net/humor/thermodynamics.html Regards, Martin From bearophileHUGS at lycos.com Tue Feb 26 18:22:16 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 26 Feb 2008 15:22:16 -0800 (PST) Subject: Indentation and optional delimiters References: <555b548f-1296-4374-b6ce-65691d1dbb7f@s8g2000prg.googlegroups.com> <13s92u3sibaus4f@corp.supernews.com> Message-ID: <3f55d3b1-c32c-42bc-bd4b-52e2725049b0@v3g2000hsc.googlegroups.com> Steven D'Aprano: > Usability for beginners is a good thing, but not at the expense of > teaching them the right way to do things. Insisting on explicit requests > before copying data is a *good* thing. If it's a gotcha for newbies, > that's just a sign that newbies don't know the Right Way from the Wrong > Way yet. The solution is to teach them, not to compromise on the Wrong > Way. I don't want to write code where the following is possible: > ... > ... suddenly my code hits an unexpected performance drop > ... as gigabytes of data get duplicated I understand your point of view, and I tend to agree. But let me express my other point of view. Computer languages are a way to ask a machine to do some job. As time passes, computers become faster, and people find that it becomes possible to create languages that are higher level, that is often more distant from how the CPU actually performs the job, allowing the human to express the job in a way closer to how less trained humans talk to each other and perform jobs. Probably many years ago a language like Python was too much costly in terms of CPU, making it of little use for most non-toy purposes. But there's a need for higher level computer languages. Today Ruby is a bit higher-level than Python (despite being rather close). So my mostly alternative answers to your problem are: 1) The code goes slow if you try to perform that operation? It means the JIT is "broken", and we have to find a smarter JIT (and the user will look for a better language). A higher level language means that the user is more free to ignore what's under the hood, the user just cares that the machine will perform the job, regardless how, the user focuses the mind on what job to do, the low level details regarding how to do it are left to the machine. It's a job of the JIT writers to allow the user to do such job anyway. So the JIT must be even smarter, and for example it partitions the 1 GB of data in blocks, each one of them managed with copy-on-write, so maybe it just copies few megabytes or memory. Such language may need to be smart enough. Despite that I think today lot of people that have a 3GHZ CPU that may accept to use a language 5 times slower than Python, that for example uses base-10 floating point numbers (they are different from Python Decimal numbers). Almost every day on the Python newsgroup a newbie asks if the round() is broken seeing this: >>> round(1/3.0, 2) 0.33000000000000002 A higher level language (like Mathematica) must be designed to give more numerically correct answers, even if it may require more CPU. But such language isn't just for newbies: if I write a 10 lines program that has to print 100 lines of numbers I want it to reduce my coding time, avoiding me to think about base-2 floating point numbers. If the language use a higher-level numbers by default I can ignore that problem, and my coding becomes faster, and the bugs decrease. The same happens with Python integers: they don't overflow, so I may ignore lot of details (like taking care of possible oveflows) that I have to think about when I use the C language. C is faster, but such speed isn't necessary if I need to just print 100 lines of output with a 3 GHz PC. What I need in such situation is a language that allows me to ignore how numbers are represented by the CPU, and prints the correct numbers on the file. This is just a silly example, but it may show my point of view (another example is below). 2) You don't process gigabytes of data with this language, it's designed to solve smaller problems with smaller datasets. If you want to solve very big problems you have to use a lower level language, like Python, or C, or assembly. Computers allow us to solve bigger and bigger problems, but today the life is full of little problems too, like processing a single 50-lines long text file. 3) You buy an even faster computer, where even copying 1 GB of data is fast enough. Wolfram: >Have a look at Tools/Scripts/pindent.py Oh, that's it, almost. Thank you. Bye, bearophile ----------------------- Appendix: Another example, this is a little problem from this page: http://www.faqs.org/docs/abs/HTML/writingscripts.html >Find the sum of all five-digit numbers (in the range 10000 - 99999) containing exactly two out of the following set of digits: { 4, 5, 6 }. These may repeat within the same number, and if so, they count once for each occurrence.< I can solve it in 3.3 seconds on my old PC with Python like this: print sum(n for n in xrange(10000, 100000) if len(set(str(n)) & set("456")) == 2) [Note: that's the second version of the code, the first version was buggy because it contained: ... & set([4, 5, 6]) So I have used the Python shell to see what set(str(12345))&set("456") was, the result was an empty set. So it's a type bug. A statically language like D often can't catch such bugs anyway, because chars are seen as numbers.] In Python I can write a low-level-style code like this that requires only 0.4 seconds with Psyco (it's backported from the D version, because it has allowed me to think at lower-level. I was NOT able to reach such low level and high speed writing a progam just for Psyco): def main(): digits = [0] * 10 tot = 0 for n in xrange(10000, 100000): i = n digits[4] = 0 digits[5] = 0 digits[6] = 0 digits[i % 10] = 1; i /= 10 digits[i % 10] = 1; i /= 10 digits[i % 10] = 1; i /= 10 digits[i % 10] = 1; i /= 10 digits[i % 10] = 1 if (digits[4] + digits[5] + digits[6]) == 2: tot += n print tot import psyco; psyco.bind(main) main() Or I can solve it in 0.07 seconds in D language (and about 0.05 seconds in very similar C code with -O3 -fomit-frame-pointer): void main() { int tot, d, i; int[10] digits; for (uint n = 10_000; n < 100_000; n++) { digits[4] = 0; digits[5] = 0; digits[6] = 0; i = n; digits[i % 10] = 1; i /= 10; digits[i % 10] = 1; i /= 10; digits[i % 10] = 1; i /= 10; digits[i % 10] = 1; i /= 10; digits[i % 10] = 1; if ((digits[4] + digits[5] + digits[6]) == 2) tot += n; } printf("%d\n", tot); } Assembly may suggest a bit lower level ways to solve the same problem (using an instruction to compute div and mod at the same time, that can go in EAX and EDX?), etc. But if I just need to solve that "little" problem once, I may want to reduce the sum of programming time + running time, so the in such situation the first Python version wins (despite the quickly fixed bug). That's why today people often use Python instead of C for small problems. Similar things can be said about a possible language that is a little higher level than Python. Bye, bearophile From ggpolo at gmail.com Wed Feb 13 16:05:49 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 13 Feb 2008 19:05:49 -0200 Subject: Email Directly from python In-Reply-To: References: Message-ID: 2008/2/13, brad : > I'd like to send email directly from within python without having to > rely on an external smtp server. You know, something like the good, old > Unix... > > echo My_message | mail -s Subject person at someplace.com I hope to not disappoint you, but mail will invoke a smtp server to send your mail. > > Can Python do something similar in a portable fashion without a smtp > server installed on the machine? You can use a smtp server that is installed somewhere else. > > Thanks, > Brad > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From pavlovevidence at gmail.com Sat Feb 16 21:21:40 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 16 Feb 2008 18:21:40 -0800 (PST) Subject: How about adding rational fraction to Python? References: <61ibo1F1uqso2U1@mid.uni-berlin.de> <188be6e9-bc05-4a72-924b-1de184980002@n58g2000hsf.googlegroups.com> <9b166b3d-89df-4f26-956a-abbd391167e7@i12g2000prf.googlegroups.com> <13rcd3nskgpv91d@corp.supernews.com> <13rde22ktgpu532@corp.supernews.com> <26641b5f-d6cb-45a6-8736-7d130d1a5aee@u10g2000prn.googlegroups.com> <13a4316e-3ce7-4b3e-b418-6efb988a8845@q78g2000hsh.googlegroups.com> <676ca28c-b471-41c8-8661-fcd2ea8c23f0@i12g2000prf.googlegroups.com> <74b95b3b-1d6a-42a6-b55d-e77a868b1ffe@64g2000hsw.googlegroups.com> Message-ID: <70ecaf16-7308-455f-9048-730b2b2f9f2f@p43g2000hsc.googlegroups.com> On Feb 16, 7:54 pm, Jeff Schwab wrote: > Carl Banks wrote: > > On Feb 16, 5:51 pm, Jeff Schwab wrote: > >> Carl Banks wrote: > >>> On Feb 16, 3:03 pm, Lie wrote: > >>>> Although rationals have its limitations too, it is a much > >>>> better choice compared to floats/Decimals for most cases. > >>> Maybe that's true for your use cases, but it's not true for most cases > >>> in general. > >>> Rationals are pretty useless for almost any extended calculations, > >>> since the denominator tends to grow in size till it's practically > >>> unusbale, > >> What do you mean by "practically unusable?" > > > So big that a fraction takes 10 minutes to reduce to simplest form and/ > > or your hard disk starts thrashing. > > > It can easily happen with seemingly innocuous calculations. > > >> I heard similar arguments > >> made against big integers at one point ("Primitive types are usually big > >> enough, why risk performance?") but I fell in love with them when I > >> first saw them in Smalltalk, and I'm glad Python supports them natively. > > > It's not the same argument, though. > > > Repeated calculations don't make bignums too large to manage unless > > they're growing it exponentially. > > > With rationals, the accumulating calculations usually makes the > > denominator grow out of control (unless there's some mitigating > > factor, like in Paul Rubin's example where there were only a ever few > > denominators.) > > OK, thanks for explaining. It doesn't seem to me intuitively like > something that would be a problem, but I'm willing to take your word for it. Consider what happens when you add two fractions: 1/2 + 1/5 To do that, you have to take the LCD of the denomintor, in this case 10, so you get 5/10 + 2/10 = 7/10 Now imagine that you're adding a lot of different numbers with a lot of different bases. That LCD's going to be pretty big. To make matters worse, imagine taking this number as the divisor in a later calculation: a new denominator would appear (7). So you get denominators that you didn't even input, which can make LCDs go higher. Any iteration with repeated divisions and additions can thus run the denominators up. This sort of calculation is pretty common (examples: compound interest, numerical integration). The thing I don't like about rationals is that they give a false sense of security. They are performing reasonably, and then you make a slight change or some circumstance changes slightly and suddenly they blow up. Carl Banks From bearophileHUGS at lycos.com Tue Feb 12 17:47:15 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 12 Feb 2008 14:47:15 -0800 (PST) Subject: ways to declare empty set variable References: <56a14$47b1a306$839b8704$9583@news2.tudelft.nl> <5099c$47b1a77b$839b8704$11089@news2.tudelft.nl> <7xhcgd7tof.fsf@ruckus.brouhaha.com> Message-ID: <719e7c26-7d52-4b78-875c-fc7d5ca32f4e@s19g2000prg.googlegroups.com> Paul Rubin: > In 3.0 you may be able to say {,} but there is a contingent that would > just as soon get rid of all that special syntax, so you'd say list() > instead of [], dict() instead of {}, etc. For Python 3.0 I'd like {} for the empty set and {:} for the empty dict, but that idea was refused time ago, probably for some mental backward compatibility. Missing that, I think dict() and set() and tuple() and list() look better than using {} for the empty dict and {/} for the empty set and () for empty tuple (or {} for the empty dict and set() for the empty set). dict() is a bit more verbose than {}, but it doesn't matter much. With those dict(), set(), tuple(), list() the only little wart left is the unary tuple literal: x, that I don't like much, maybe I'd like tuple to be identified by a pair of delimiters, maybe like [|x|] or something like that as in the Fortress language. I don't know... Bye, bearophile From dblubaugh at belcan.com Fri Feb 1 10:43:50 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Fri, 1 Feb 2008 10:43:50 -0500 Subject: MyHDL project !!!!! In-Reply-To: References: Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F380239F9AE@AWMAIL04.belcan.com> Dan, I would be honored to start a project such as that in mind. How do we begin ?????? David Blubaugh -----Original Message----- From: chewie54 [mailto:dfabrizio51 at gmail.com] Sent: Thursday, January 31, 2008 9:34 PM To: python-list at python.org Subject: Re: Will Python on day replaceMATLAB????????????????????????????????????????????????????? > I have been evaluating the python environment ever more closer. I > believe I can interface python with a development environment known as > the ImpulseC environment. The ImpulseC environment develops C to VHDL > for FPGA development. I would especially love to interface Python > with ImpulseC and the graphing capabilities of GNU Plot and SciPy in > order to recreate a VHDL development environment that will be just as > capable as a $50,000 dollar Matlab to VHDL toolbox. This is also a > part of my Masters thesis. Is anyone willing to help in this endeavor????? > > David Blubaugh > Why not use MyHDL which is written in Python and translates to Verilog. I assume ImpulseC is a commercial product and costs a log. MyHDL is free. If you have any interests in combining MyHDL with SciPy and NumPy I would be interested in getting involved. Dan Fabrizio This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From nagle at animats.com Sun Feb 3 03:36:56 2008 From: nagle at animats.com (John Nagle) Date: Sun, 03 Feb 2008 00:36:56 -0800 Subject: "ping" not reconnecting in Python MySQLdb client interface Message-ID: <47A57D28.5000304@animats.com> I have some long-running Python programs that can be idle for hours, and, of course, the MySQL connection times out. So I call db.ping() at the beginning of a new request cycle. This should reestablish the connection, but it doesn't: Traceback (most recent call last): File "rateapiv1.fcgi", line 60, in QuickSitetruthQuery db.ping() # reattach connection if necessary OperationalError: (2006, 'MySQL server has gone away') The MySQL server is up, and new connection attempts succeed. This problem was reported two years ago relative to TurboGears: http://trac.turbogears.org/ticket/872 I suspect that MySQL has auto-reconnect turned off, but doesn't document this. (MySQL 5 on Fedora Core) John Nagle From roy at panix.com Sun Feb 17 09:44:20 2008 From: roy at panix.com (Roy Smith) Date: Sun, 17 Feb 2008 09:44:20 -0500 Subject: sockets -- basic udp client References: <37cfdc95-5aa0-4b47-9dc6-d54f7ac254a6@v3g2000hsc.googlegroups.com> <8f768bd3-ec74-4f0d-bbc2-4407b2d7b46a@60g2000hsy.googlegroups.com> Message-ID: In article "rluse1 at gmail.com" wrote: > If you don't care about the address of the sender, e.g. you are not > going to send anything back, is there an advantage to using recv()? At the system call level, recv() is marginally faster since there's less data to pass back and forth between the kernel and user space. Not that this is likely to be significant in any real-world application. The bigger advantage to recv() is that the interface is simpler, so there's less code to write. For the C interface, using recv() instead of recvfrom() frees you from having to pass in two arguments that you're not going to use. From the Python interface, it frees you from having to unpack the tuple that recvfrom() returns. Instead of: data, address = recvfrom(bufsize) you write data = recv(bufsize) It's not just a bunch less typing, it's also easier to understand. You don't leave some future maintainer of your code scratching their head trying to figure out where 'address' is used, when in fact, it's not. From AWasilenko at gmail.com Sun Feb 17 18:07:02 2008 From: AWasilenko at gmail.com (Adam W.) Date: Sun, 17 Feb 2008 15:07:02 -0800 (PST) Subject: Dont know what my class is called... Message-ID: <04fd5bb1-1101-4833-9260-c1ae8985e06a@d5g2000hsc.googlegroups.com> I am using the xml.sax package, and I'm running into a little problem. When I use the parse(url, ContentHandler()) method, I don't know what parse() is naming the instance of ContentHandler. I have a sub-class of ContentHandler make a dictionary of what it parses, but the problem is I don't know the name of instance for me to get at it. The only way I have gotten at my dict is to declare it a global value, and I know that is not the right way to do it. I though I would be clever and put "print self" inside the __int__ method of the ContentHandler sub-class, in hopes it would display its given name, but it returned a rather useless: <__main__.FeedHandler instance at 0x02D8B5D0> So, any ideas on how to figure this out would be great. From nitro at dr-code.org Tue Feb 26 16:39:02 2008 From: nitro at dr-code.org (Nitro) Date: Tue, 26 Feb 2008 22:39:02 +0100 Subject: time.time() strangeness Message-ID: > Nevertheless time.time() shouldn't fail here unless DirectX is really > badly tinkering with my system. I can tell you more now. If I pass D3DCREATE_FPU_PRESERVE while creating the DirectX device the bug does not appear. This flag means "Direct3D defaults to single-precision round-to-nearest" (see [1]) mode. Unfortunately it is not an option to pass this flag, I need the performance boost it gives. Can somebody tell me how this interacts with python's time.time()? I suppose it's some kind of double vs. float thing or some fpu asm code issue... -Matthias References: [1] http://msdn2.microsoft.com/en-us/library/bb172527(VS.85).aspx From oinopion at gmail.com Fri Feb 8 16:24:18 2008 From: oinopion at gmail.com (Tomek Paczkowski) Date: Fri, 08 Feb 2008 22:24:18 +0100 Subject: Critique of first python code References: Message-ID: <47acc881$0$6192$f69f905@mamut2.aster.pl> Zack wrote: > Hi all. I'm just starting to pick up python. I wanted to play with nested > lists so first I wrote a little bit of code to create arbitrarily nested > lists (grow). Then I wrote a breadth first search. I'm putting this small > snippet up asking for criticism. Was there a more elegant way to do what > ... You can try to put your code through pylint. It will give you some automatic critique. -- Oinopion From castironpi at gmail.com Sat Feb 16 19:07:24 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 16 Feb 2008 16:07:24 -0800 (PST) Subject: An idea for fast function composition References: <2c092327-38d0-4624-8b24-a8a8a414b078@d5g2000hsc.googlegroups.com> Message-ID: <4c4aa040-9624-49c1-a0c7-11ac6d21d03a@n77g2000hse.googlegroups.com> On Feb 16, 5:57?pm, Boris Borcic wrote: > castiro... at gmail.com wrote: > > On Feb 16, 3:47 pm, Arnaud Delobelle wrote: > >> Hi all, > > >> Recently there was a thread about function composition in Python (and > >> this was probably not the first). ?The fast way to create a > >> (anonymous) composite function > > >> ? ? ?f1 o f2 o ... o fn > > >> in Python is via > > >> ? ? ?lambda x: f1(f2(...fn(x)...)), > > >> but according to some this is neither the most compact nor the most > >> readable. ?Below I define a 'compose' function such that the above can > >> be written > > >> ? ? ?compose(f1, f2, ...., fn), > > >> the resulting function being as fast as the lambda version (or maybe > >> faster?). ?'getcomposer' is a helper function (which in most cases > >> will amount to a dictionary lookup). > > >> ---------------------------------- > >> def getcomposer(nfunc, _cache={}): > >> ? ? ?"getcomposer(n) -> lambda f1, ..., fn:(lambda x: f1(...fn(x)...))" > >> ? ? ?try: > >> ? ? ? ? ?return _cache[nfunc] > >> ? ? ?except KeyError: > >> ? ? ? ? ?fnames = ['f%s' % i for i in range(nfunc)] > >> ? ? ? ? ?call = ''.join('%s(' % f for f in fnames) > >> ? ? ? ? ?args = ','.join(fnames) > >> ? ? ? ? ?cstr = 'lambda %s:(lambda x:%sx%s)' % (args, call, ')'*nfunc) > >> ? ? ? ? ?composer = _cache[nfunc] = eval(cstr) > >> ? ? ? ? ?return composer > > >> def compose(*functions): > >> ? ? ?"compose(f1, ..., fn) -> lambda x: f1(f2(...fn(x)...))" > >> ? ? ?return getcomposer(len(functions))(*functions) > > >> # Test > > >> def double(x): return 2*x > >> def square(x): return x**2 > >> def succ(x): return x+1 > > >> f1 = compose(double, square, succ, float) > >> f2 = lambda x: double(square(succ(float(x)))) > > >> def benchmark(f, n=1000000): > >> ? ? ?from time import time > >> ? ? ?from itertools import imap > >> ? ? ?t0 = time() > >> ? ? ?for _ in imap(f1, xrange(n)): pass > >> ? ? ?t1 = time() > >> ? ? ?return t1-t0 > > >> print 'compose', benchmark(f1) > >> print 'lambda ', benchmark(f2) > >> ---------------------------------- > > >> marigold:python arno$ python -i simple_compose.py > >> compose 1.84630298615 > >> lambda ?1.86365509033 > >> ?>>> import dis > >> ?>>> dis.dis(f1) > >> ? ?1 ? ? ? ? ? 0 LOAD_DEREF ? ? ? ? ? ? ? 0 (f0) > >> ? ? ? ? ? ? ? ?3 LOAD_DEREF ? ? ? ? ? ? ? 3 (f1) > >> ? ? ? ? ? ? ? ?6 LOAD_DEREF ? ? ? ? ? ? ? 1 (f2) > >> ? ? ? ? ? ? ? ?9 LOAD_DEREF ? ? ? ? ? ? ? 2 (f3) > >> ? ? ? ? ? ? ? 12 LOAD_FAST ? ? ? ? ? ? ? ?0 (x) > >> ? ? ? ? ? ? ? 15 CALL_FUNCTION ? ? ? ? ? ?1 > >> ? ? ? ? ? ? ? 18 CALL_FUNCTION ? ? ? ? ? ?1 > >> ? ? ? ? ? ? ? 21 CALL_FUNCTION ? ? ? ? ? ?1 > >> ? ? ? ? ? ? ? 24 CALL_FUNCTION ? ? ? ? ? ?1 > >> ? ? ? ? ? ? ? 27 RETURN_VALUE > >> ?>>> dis.dis(f2) > >> ? 23 ? ? ? ? ? 0 LOAD_GLOBAL ? ? ? ? ? ? ?0 (double) > >> ? ? ? ? ? ? ? ?3 LOAD_GLOBAL ? ? ? ? ? ? ?1 (square) > >> ? ? ? ? ? ? ? ?6 LOAD_GLOBAL ? ? ? ? ? ? ?2 (succ) > >> ? ? ? ? ? ? ? ?9 LOAD_GLOBAL ? ? ? ? ? ? ?3 (float) > >> ? ? ? ? ? ? ? 12 LOAD_FAST ? ? ? ? ? ? ? ?0 (x) > >> ? ? ? ? ? ? ? 15 CALL_FUNCTION ? ? ? ? ? ?1 > >> ? ? ? ? ? ? ? 18 CALL_FUNCTION ? ? ? ? ? ?1 > >> ? ? ? ? ? ? ? 21 CALL_FUNCTION ? ? ? ? ? ?1 > >> ? ? ? ? ? ? ? 24 CALL_FUNCTION ? ? ? ? ? ?1 > >> ? ? ? ? ? ? ? 27 RETURN_VALUE > > >> f1 and f2 are almost exaclty the same but array lookups (LOAD_DEREFs) > >> in f1 replace dictionary lookups (LOAD_GLOBALs) in f2. ?A C version of > >> 'compose' could easily be written that doesn't require the use of a > >> python lambda-function (as created by 'getcomposer'). > > >> -- > >> Arnaud > > > def compose( funcs ): > > ? ?def reccompose( *args ): > > ? ? ? return compose( funcs[:-1] )( funcs[-1]( *args ) ) if funcs else > > funcs[0]( *args ) > > ? ?return reccompose > > ?>>> def compose( *funcs ): > ? ? ? ? def reccompose( *args ): > ? ? ? ? ? ? ? ? return compose( funcs[:-1] )( funcs[-1]( *args ) ) if funcs else funcs[0]( *args ) > ? ? ? ? return reccompose > > ?>>> f3 = compose(double, square, succ, float) > ?>>> import dis > ?>>> dis.dis(f3) > ? ?3 ? ? ? ? ? 0 LOAD_DEREF ? ? ? ? ? ? ? 0 (funcs) > ? ? ? ? ? ? ? ?3 JUMP_IF_FALSE ? ? ? ? ? 33 (to 39) > ? ? ? ? ? ? ? ?6 POP_TOP > ? ? ? ? ? ? ? ?7 LOAD_GLOBAL ? ? ? ? ? ? ?0 (compose) > ? ? ? ? ? ? ? 10 LOAD_DEREF ? ? ? ? ? ? ? 0 (funcs) > ? ? ? ? ? ? ? 13 LOAD_CONST ? ? ? ? ? ? ? 1 (-1) > ? ? ? ? ? ? ? 16 SLICE+2 > ? ? ? ? ? ? ? 17 CALL_FUNCTION ? ? ? ? ? ?1 > ? ? ? ? ? ? ? 20 LOAD_DEREF ? ? ? ? ? ? ? 0 (funcs) > ? ? ? ? ? ? ? 23 LOAD_CONST ? ? ? ? ? ? ? 1 (-1) > ? ? ? ? ? ? ? 26 BINARY_SUBSCR > ? ? ? ? ? ? ? 27 LOAD_FAST ? ? ? ? ? ? ? ?0 (args) > ? ? ? ? ? ? ? 30 CALL_FUNCTION_VAR ? ? ? ?0 > ? ? ? ? ? ? ? 33 CALL_FUNCTION ? ? ? ? ? ?1 > ? ? ? ? ? ? ? 36 JUMP_FORWARD ? ? ? ? ? ?14 (to 53) > ? ? ? ? ?>> ? 39 POP_TOP > ? ? ? ? ? ? ? 40 LOAD_DEREF ? ? ? ? ? ? ? 0 (funcs) > ? ? ? ? ? ? ? 43 LOAD_CONST ? ? ? ? ? ? ? 2 (0) > ? ? ? ? ? ? ? 46 BINARY_SUBSCR > ? ? ? ? ? ? ? 47 LOAD_FAST ? ? ? ? ? ? ? ?0 (args) > ? ? ? ? ? ? ? 50 CALL_FUNCTION_VAR ? ? ? ?0 > ? ? ? ? ?>> ? 53 RETURN_VALUE > > Mmmhhh...- Hide quoted text - > > - Show quoted text - OOOOOOwwwwwwww! From adam at volition-inc.com Sun Feb 3 20:39:41 2008 From: adam at volition-inc.com (Adam Pletcher) Date: Sun, 3 Feb 2008 19:39:41 -0600 Subject: python for game programming References: Message-ID: <893A44FF792E904A97B7515CE3419146F1EBC9@volimxs01.thqinc.com> In addition to EVE Online, Disney's Toontown Online is another example, along with Psi-Ops and Civ 4. Irrational, DICE, Totally Games and Troika all reportedly use Python in some capacity, either for gameplay scripting or as a development tool. At GDC 2008, a couple weeks from now, there are two sessions on Python. I'm presenting the first one below, which focuses on Python as a game development tool for TAs: Python for Technical Artists https://www.cmpevents.com/GD08/a.asp?option=C&V=11&SessID=6459 The other one, from the runtime front: Snakes on a Seamless Living World!: Stackless Python as a Scripting Language https://www.cmpevents.com/GD08/a.asp?option=C&V=11&SessID=6464 This goes back to 2002, but here's a good article from Bruce Dawson on the use of Python for gameplay scripting. http://www.gamasutra.com/view/feature/2963/gdc_2002_game_scripting_in_python.php -- Adam Pletcher Technical Art Director Volition/THQ www.volition-inc.com ________________________________ From: python-list-bounces+adam=volition-inc.com at python.org on behalf of t3chn0n3rd Sent: Sun 2/3/2008 8:05 AM To: python-list at python.org Subject: python for game programming Is Python program language popular for game programming? -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From http Sun Feb 10 17:38:17 2008 From: http (Paul Rubin) Date: 10 Feb 2008 14:38:17 -0800 Subject: Turn off ZeroDivisionError? References: <63d2e7d1-aa26-4ddc-9d12-42ae636104c1@s37g2000prg.googlegroups.com> <13qunlu5nrva731@corp.supernews.com> <13qusltq0v8vt39@corp.supernews.com> Message-ID: <7xtzkgphd2.fsf@ruckus.brouhaha.com> Christian Heimes writes: > Python targets both newbies and professionals. > That's the reason for two math modules (math and cmath). Ehhh??? cmath is for complex-valued functions, nothing to do with newbies vs. professionals. From Lie.1296 at gmail.com Tue Feb 26 06:50:40 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 26 Feb 2008 03:50:40 -0800 (PST) Subject: How about adding rational fraction to Python? References: <676ca28c-b471-41c8-8661-fcd2ea8c23f0@i12g2000prf.googlegroups.com> <74b95b3b-1d6a-42a6-b55d-e77a868b1ffe@64g2000hsw.googlegroups.com> <70ecaf16-7308-455f-9048-730b2b2f9f2f@p43g2000hsc.googlegroups.com> <13rf9tvbkt66r2a@corp.supernews.com> <198927a7-9478-42b3-a972-82049f0130ac@u10g2000prn.googlegroups.com> <1bc9bba7-dc7f-4cfe-8e1c-fa5901c9f556@n77g2000hse.googlegroups.com> <97f30679-483d-4751-9a6e-0858b36eb426@d4g2000prg.googlegroups.com> <13s3sktkj902tac@corp.supernews.com> Message-ID: <556bfa1f-a5e1-48dc-9e42-d837e57e0e62@28g2000hsw.googlegroups.com> On Feb 25, 5:41 am, Steven D'Aprano wrote: > On Sun, 24 Feb 2008 10:09:37 -0800, Lie wrote: > > On Feb 25, 12:46 am, Steve Holden wrote: > >> Lie wrote: > >> > On Feb 18, 1:25 pm, Carl Banks wrote: > >> >> On Feb 17, 1:45 pm, Lie wrote: > > >> >>>> Any iteration with repeated divisions and additions can thus run > >> >>>> the denominators up. This sort of calculation is pretty common > >> >>>> (examples: compound interest, numerical integration). > >> >>> Wrong. Addition and subtraction would only grow the denominator up > >> >>> to a certain limit > >> >> I said repeated additions and divisions. > > >> > Repeated Addition and subtraction can't make fractions grow > >> > infinitely, only multiplication and division could. > > >> On what basis is this claim made? > > >> (n1/d1) + (n2/d2) = ((n1*d2) + (n2*d1)) / (d1*d2) > > >> If d1 and d2 are mutually prime (have no common factors) then it is > >> impossible to reduce the resulting fraction further in the general case > >> (where n1 = n2 = 1, for example). > > >> >> Anyways, addition and subtraction can increase the denominator a lot > >> >> if for some reason you are inputing numbers with many different > >> >> denominators. > > >> > Up to a certain limit. After you reached the limit, the fraction > >> > would always be simplifyable. > > >> Where does this magical "limit" appear from? > > >> > If the input numerator and denominator have a defined limit, repeated > >> > addition and subtraction to another fraction will also have a defined > >> > limit. > > >> Well I suppose is you limit the input denominators to n then you have a > >> guarantee that the output denominators won't exceed n!, but that seems > >> like a pretty poor guarantee to me. > > >> Am I wrong here? You seem to be putting out unsupportable assertions. > >> Please justify them or stop making them. > > > Well, I do a test on my own fraction class. I found out that if we set a > > limit to the numerators and denominators, the resulting output fraction > > would have limit too. I can't grow my fraction any more than this limit > > no matter how many iteration I do on them. I do the test is by something > > like this (I don't have the source code with me right now, it's quite > > long if it includes the fraction class, but I think you could use any > > fraction class that automatically simplify itself, might post the real > > code some time later): > > > while True: > > a = randomly do (a + b) or (a - b) > > b = random fraction between [0-100]/[0-100] print a > > > And this limit is much lower than n!. I think it's sum(primes(n)), but > > I've got no proof for this one yet. > > *jaw drops* > > Please stop trying to "help" convince people that rational classes are > safe to use. That's the sort of "help" that we don't need. > > For the record, it is a perfectly good strategy to *artificially* limit > the denominator of fractions to some maximum value. (That's more or less > the equivalent of setting your floating point values to a maximum number > of decimal places.) But without that artificial limit, repeated addition > of fractions risks having the denominator increase without limit. > > -- > Steven No, it is a real limit. This is what I'm talking about. If the input data has a limit, the output data has a real limit, not a defined- limit. If the input data's denominator is unbounded, the output fraction's denominator is also unbounded In a repeated addition and subtraction with input data that have limits From steve at holdenweb.com Sat Feb 16 17:35:31 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 16 Feb 2008 17:35:31 -0500 Subject: Solve a Debate In-Reply-To: <5cd4a65b-2eb0-44a4-a2bf-49c8d602111a@n75g2000hsh.googlegroups.com> References: <5cd4a65b-2eb0-44a4-a2bf-49c8d602111a@n75g2000hsh.googlegroups.com> Message-ID: castironpi at gmail.com wrote: > On Feb 15, 11:50 pm, Steve Holden wrote: >> Dan Bishop wrote: >>> On Feb 15, 10:24 am, nexes wrote: [...] >>>> What are everyone else's thoughts on this? >>> days_in_month = lambda m: m - 2 and 30 + bool(1 << m & 5546) or 28 >> Elegant, but the 5546 is way too magical for readability. > >>>> int( '0101010110101'[::-1], 2 ) > 5546 Yes, I'm aware of that. Adding it as a comment might help. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From dotancohen at gmail.com Thu Feb 7 20:28:39 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Fri, 8 Feb 2008 03:28:39 +0200 Subject: Microsoft's challenger to Python In-Reply-To: References: <47AB9D50.5050503@bmm.com> <880dece00802071708m618a8750w5f5709c57ec0ec59@mail.gmail.com> Message-ID: <880dece00802071728p1c898015qce015aeb30981760@mail.gmail.com> On 08/02/2008, Guilherme Polo wrote: > > > I am not, however, an in depth language nutter, so would > > > appreciate any of our more learned readers comments. > > > > Looks like MS forgot E and E and went straight for E this time. > > I couldn't understand what you said, maybe that a E language doesnt > yet exist? It does: http://www.erights.org/ http://en.wikipedia.org/wiki/Embrace%2C_extend%2C_and_extinguish In any case, I'm certain that only certain 'features' will work on Linux, or some terrible security bug will be found in the Linux version (because of a fault of Linux, no doubt). Almost certainly, the runtime environment will not be compatible with accepted licencing policies of popular Linux distributions, ensuring that said bug will never be fixed and will give MS lots of juicy FUD for smear campaigns. Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From mastastealth at gmail.com Tue Feb 5 08:50:25 2008 From: mastastealth at gmail.com (Mastastealth) Date: Tue, 5 Feb 2008 05:50:25 -0800 (PST) Subject: Binary file Pt 1 - Only reading some References: <7eeb518c-f607-4315-8a4c-4ca7b590520d@y5g2000hsf.googlegroups.com> Message-ID: On Feb 5, 1:17?am, Gabriel Genellina wrote: > Using the struct module ?http://docs.python.org/lib/module-struct.html > > import struct > data = info.read(15) > str1, str2, blank, height, width, num2, num3 = > struct.unpack("6s3s1cBBBh", data) > > Consider this like a "first attempt", open issues: is the data little- > endian or big-endian? does the 0-5 mean 0x00-0x05 or "0"-"5"? the last > numbers are 2-byte binary integers, or 0000-0899 might indicate BDC? > But building the right format is surely faster and easier than parsing > the data by hand. > > -- > Gabriel Genellina Ah ok, thanks! That worked, though the line "str1, str2, blank, height, width, num2, num3 =" spit out a syntax error. However, I do see that it creates a tuple with all the values in a readable format for me. Also, I needed to change info.read(15) to 16. More questions: What is this value for? "6s3s1cBBBh" and why is my unpack limited to a length of "16"? Unfortunately it seems my understanding of binary is way too basic for what I'm dealing with. Can you point me to a simple guide to explaining most of it? As far as I know this is just a bunch of 1's and 0's right? Each byte has 8 digits of, of which somehow is converted to a number or letter. Don't know what most of that stuff in the struct page means. -_- As for you questions, I suppose it would be "little-endian" as the format is on PC (and the Python docs say: "Intel and DEC processors are little-endian"). 0-5 means a single digit "0" through "5". Lastly, I'm not building the format, it's already made (a format for tiled maps in a game). My program is just reading it. From stef.mientki at gmail.com Mon Feb 4 17:17:42 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 04 Feb 2008 23:17:42 +0100 Subject: (websearch) script ? Message-ID: <47A78F06.1040605@gmail.com> hello, Being very satisfied with Python as a general program language, and having troubles with a number of PHP scripts, moving to another provider, I wanted to replace the PHP scripts with Python Scripts. The most important one is a PHP script that searches text in all documents on my website. Does someone has such a script ? Now in more general, If I need such a script in PHP or Perl, I can find dozens on the web, for Python I can not find None ??? Am I mistaken that these kind of tasks can be equally well performed by Python as PHP or Perl ? If so, why can't I find all kinds of standard scripts on the web ? Just curious. thanks, Stef Mientki From ggpolo at gmail.com Thu Feb 7 10:46:20 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 7 Feb 2008 13:46:20 -0200 Subject: Looking for library to estimate likeness of two strings In-Reply-To: <38730101-450c-4c1c-8ef1-70660dc7ef4e@k39g2000hsf.googlegroups.com> References: <86e63d06-124e-49e8-82e2-dfbea01fcce7@v17g2000hsa.googlegroups.com> <38730101-450c-4c1c-8ef1-70660dc7ef4e@k39g2000hsf.googlegroups.com> Message-ID: 2008/2/7, agenkin at gmail.com : > On Feb 7, 2:37 am, "Daniel Fetchinson" > wrote: > > > Hi folks, just went through this thread and a related one from 2006 > > and I was wondering what the best solution is for using these string > > metrics in a database search. If I want to query the database for a > > string or something that is close to it (close being defined by one of > > the string metrics discussed above) it seems I have to select each and > > every word from the database and compare it with the query word which > > is very ineffective. > > > I have never used sqlite database, but Postgres has a module that > implements levenshtein(), soundex() and metaphone() functions, so you > can do something like this: > > SELECT * FROM s WHERE soundex(name) = soundex('john'); > SELECT * FROM s WHERE difference(name, 'john') > 2; > > http://www.postgresql.org/docs/8.3/static/fuzzystrmatch.html > SQLite supports soundex, but it is disabled by default, you need to compile it with -DSQLITE_SOUNDEX=1 > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From kwa at kuwata-lab.com Sun Feb 24 22:38:27 2008 From: kwa at kuwata-lab.com (makoto kuwata) Date: Sun, 24 Feb 2008 19:38:27 -0800 (PST) Subject: Question about PyPI and 'easy_install' Message-ID: <700d4ba3-e088-4c7d-a4d8-96b68dccb61e@71g2000hse.googlegroups.com> Hi, I have a trouble around PyPI and easy_install. I have developed OSS (Tenjin) and registered it to PyPI. http://pypi.python.org/pypi/Tenjin/0.6.1 But I can't install it by 'easy_install' command. $ easy_install Tenjin Searching for Tenjin Reading http://pypi.python.org/simple/Tenjin/ Reading http://www.kuwata-lab.com/tenjin/ No local packages or download links found for Tenjin error: Could not find suitable distribution for Requirement.parse('Tenjin') This error reports that download link is not found, but download url is described in the above web page. Could you help me why the above error happen? Is it required to set registered name (Tenjin) and package name (pyTenjin) into same name? -- makoto kuwata From jwashin at nospam.hill-street.net Fri Feb 15 10:47:38 2008 From: jwashin at nospam.hill-street.net (Jim Washington) Date: Fri, 15 Feb 2008 15:47:38 GMT Subject: RELEASED zif.sedna 0.9 beta2 Message-ID: zif.sedna provides python access to the very cool XML database, Sedna, available at http://modis.ispras.ru/sedna/, under Apache 2.0 license. It's not about kool-aid or sit-ups. It's another option for storing, modifying, and retrieving hierarchical data. zif.sedna is available from the Python Package Index. zif.sedna provides a dbapi-like interface (connections and cursors). zif.sedna provides a database adapter for Zope(3) and now has preliminary instructions for use with pylons. Sedna is a product of the Sedna Team at the Institute for System Programming, Russian Academy of Sciences . zif.sedna is just an adapter package. -Jim Washington From steve at holdenweb.com Wed Feb 6 11:51:04 2008 From: steve at holdenweb.com (Steve Holden) Date: Wed, 06 Feb 2008 11:51:04 -0500 Subject: Why not a Python compiler? In-Reply-To: References: <28eead2f-a40c-414b-bd3d-a941f8a851a2@d70g2000hsb.googlegroups.com><7da40f42-f64f-4939-a0dc-d24d1ff85f2d@v4g2000hsf.googlegroups.com> <13qjktdbe76da00@corp.supernews.com> Message-ID: <47A9E578.2090107@holdenweb.com> Reedick, Andrew wrote: >> -----Original Message----- >> From: python-list-bounces+jr9445=att.com at python.org [mailto:python- >> list-bounces+jr9445=att.com at python.org] On Behalf Of Grant Edwards >> Sent: Wednesday, February 06, 2008 10:35 AM >> To: python-list at python.org >> Subject: Re: Why not a Python compiler? >> >> On 2008-02-06, Reedick, Andrew wrote: >> >>>> Pypy is a very ambitious project and it aims, amongst many >>>> other goals, to provide a fast just-in-time python >>>> implementation. They even say that the "secret goal is being >>>> faster than c, which is nonsense, isn?t it?" (I still didn?t >>>> get the joke though...). >>> 'c' is also the speed of light. >> 'c' is the speed of light _in_a_vacuum_. > > True. > > >>> And since nothing can travel faster than light... >> Nothing can travel faster than the speed of light >> _in_a_vacuum_. There are situtaitons where things can (and >> regularly do) travel faster than light: >> http://en.wikipedia.org/wiki/Cherenkov_radiation > > > Nope. It propagates, not travels, faster than light. Go ask a physicist to explain it. It's odd... > > >>> One demerit has been marked against your geek card for missing >>> an obvious science pun. Additionally, your membership to the >>> Star Trek Lifestyle Adventure Club has been put on >>> probationary status for the next twelve parsecs. >> Ouch. Two demerits for using the distance unit "parsec" in a >> context where a quantity of time was required. > > > Ten demerits for not catching the Star Wars Kessel Run reference. > > OK, now you can all take ten house points for getting into a jargon pissing contest. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From tjreedy at udel.edu Sun Feb 24 21:13:08 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 24 Feb 2008 21:13:08 -0500 Subject: Using lambda [was Re: Article of interest: Python pros/cons for theenterprise] References: <2f1527a7-2f66-44c7-9665-4d8ff01fa5ab@28g2000hsw.googlegroups.com><47bd4a24$0$25225$426a74cc@news.free.fr><036e93e6-5840-4a3c-8642-67a0a9ec44f2@i7g2000prf.googlegroups.com><784ec210-f389-4a15-b458-961100de9103@v3g2000hsc.googlegroups.com><5MSdncqVGdEXiSPanZ2dnUVZ_vPinZ2d@comcast.com><7xwsoxd00c.fsf@ruckus.brouhaha.com><7xmyprtay1.fsf@ruckus.brouhaha.com><88qdnQR0a7V7Rl3anZ2dnUVZ_rqlnZ2d@comcast.com><7xmyprf3ef.fsf@ruckus.brouhaha.com> <13s26luietu512c@corp.supernews.co m> Message-ID: "Steven D'Aprano" wrote in message news:13s26luietu512c at corp.supernews.com... | On Sat, 23 Feb 2008 19:35:30 -0800, Jeff Schwab wrote: | | > Every time somebody uses | > lambda here, they seem to get a bunch "why are you using lambda?" | > responses. I think you are overgeneralizing ;-) I use 'em. | Not from me. | | I even use "named anonymous functions" *cough* by assigning lambda | functions to names: | | foo = lambda x: x+1 Even though I consider the above to be clearly inferior to def foo(x): return x+1 since the latter names the function 'foo' instead of the generic ''. The only other situation in which I would critisize lambda usage are multi-line (or super-long-line) monstrousities that are not intentionally 'obfuscated Python'. tjr From asmodai at in-nomine.org Mon Feb 18 12:57:20 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Mon, 18 Feb 2008 18:57:20 +0100 Subject: Python 3.0 In-Reply-To: <27CC3060AF71DA40A5DC85F7D5B70F38026E5E6E@AWMAIL04.belcan.com> References: <27CC3060AF71DA40A5DC85F7D5B70F38026E5A52@AWMAIL04.belcan.com> <895f1790802151602r354bffb4pcca979c9316fecf8@mail.gmail.com> <27CC3060AF71DA40A5DC85F7D5B70F38026E5A7F@AWMAIL04.belcan.com> <895f1790802151644q70c6cec6k946b4185cb2ddc13@mail.gmail.com> <27CC3060AF71DA40A5DC85F7D5B70F38026E5E6E@AWMAIL04.belcan.com> Message-ID: <20080218175720.GK81956@nexus.in-nomine.org> -On [20080218 18:33], Blubaugh, David A. (dblubaugh at belcan.com) wrote: >Is there a logical reason why Python 3 is not backwards compatible? The sheer amount of overhaul as documented in http://www.python.org/dev/peps/pep-3100/ makes it already not backwards compatible. Python has been progressing piece by piece, but the 2.x -> 3.0 transition allows to clean up some thing in a good way, rather than bolting things on top of others. Anyway, please search around a bit, this kind of stuff has been extensively discussed in the past. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ In the dark backward and abysm of time... From nure123 at gmail.com Sat Feb 9 22:40:25 2008 From: nure123 at gmail.com (nure123 at gmail.com) Date: Sat, 9 Feb 2008 19:40:25 -0800 (PST) Subject: What is wrong with this References: <13qspuh9n2v3i85@corp.supernews.com> Message-ID: On Feb 9, 8:56 pm, Steven D'Aprano wrote: > On Sat, 09 Feb 2008 16:44:52 -0800, nure123 wrote: > > Hi, > > > I am new to Python and would be grateful if anyone could tell me what is > > wrong with the following statement. > > > Y=array([1/S, 0*lam]) > > > where > > S=[1, 2, 3, 4] > > lam=[5, 6, 7, 8] > > Oh, a guessing game! I love guessing games. > > Let's see now... did you actually want to do a Fourier transform of some > data? > > If not, perhaps you could tell us what you expected to happen, and what > actually happened, so we can stop guessing and actually help. > > -- > Steven I get an error like 'inconsistent shape in sequence.' I changed it to Y=array([1/S, zeros(len(lam))]) it works fine. But I am still interested in knowing why did the original programmer did not get any error whereas I got an error with the statement : Y=array([1/S, 0*lam]) From paul at boddie.org.uk Sun Feb 17 15:42:46 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 17 Feb 2008 12:42:46 -0800 (PST) Subject: Linux/Python Issues References: Message-ID: <8456cf3b-19e6-4695-9cbf-5f345b57e59b@e60g2000hsh.googlegroups.com> On 17 Feb, 20:38, MartinRineh... at gmail.com wrote: > I went to Python.org, DL'd Python 2.5 source code per the usual > inadequate instructions and ran the make files successfully (sort of). > Python 2.5 works fine. But "from Tkinter import *" gets a "What's > Tkinter?" message. IDLE's no where to be found. It could be that you don't have the Tcl/Tk libraries installed, or perhaps the header files for Tcl/Tk aren't installed. If so, Python wouldn't detect them when being configured itself, and then you probably wouldn't have the Tkinter extension installed. > What's not in the instructions is what directory should I be in when I > download? Where should I put the ".bz2" file? What dir for running the > make files? At present I'm working on a Windows machine, endangering > what's left of my sanity. > > I'm using Linspire, so Debian directories are probably the ones that > will get me up and running. Barring specific knowledge, even some good > guesses would be appreciated. Here's one page which probably tells you stuff you already know: http://wiki.python.org/moin/BeginnersGuide/Download On Ubuntu, which is Debian-based, the python-tk package should make Tkinter available, so you could look for that in your repositories. As for building from source, you can put the .bz2 file anywhere, and unpack it anywhere that isn't going to make a mess for you to clean up later. For example, you could download the Python .bz2 file into a "downloads" directory residing in your home directory, then you could do this: mkdir software cd software tar jxf ~/downloads/Python-2.5.1.tar.bz2 cd Python-2.5.1 ./configure make You can then do a "make install" with the right privileges. Paul From dmitrey.kroshko at scipy.org Tue Feb 5 12:42:13 2008 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Tue, 5 Feb 2008 09:42:13 -0800 (PST) Subject: future multi-threading for-loops References: <5ba19668-4eb1-430c-b1e6-d1b17de33811@s13g2000prd.googlegroups.com> Message-ID: On Feb 5, 5:22 am, castiro... at gmail.com wrote: > Some iterables and control loops can be multithreaded. Worries that > it takes a syntax change. > > for X in A: > def f( x ): > normal suite( x ) > start_new_thread( target= f, args= ( X, ) ) > > Perhaps a control-flow wrapper, or method on iterable. > > @parallel > for X in A: > normal suite( X ) > > for X in parallel( A ): > normal suite( X ) > I would propose "for X IN A" for parallel and remain "for X in A" for sequential. BTW for fortress lang I had proposed "for X <- A" and "for X <= A" for sequential/parallel instead of current "for X <- seq(A)", "for X <- A", mb they will implement my way instead. From hyugaricdeau at gmail.com Tue Feb 5 10:22:43 2008 From: hyugaricdeau at gmail.com (Hyuga) Date: Tue, 5 Feb 2008 07:22:43 -0800 (PST) Subject: How to autorun a python script when a specific user logs on? References: <47a81708$0$16675$4c368faf@roadrunner.com> Message-ID: <51d3f6e8-a6c7-485e-9bb5-313bc7a1ddc4@q21g2000hsa.googlegroups.com> You know, I'm all for responsible parenting, and teaching kids about about responsible computer use, and even to an extent checking out things like browser history to make sure they're up to no good. But this is outright spying--a total invasion of privacy. Might as well put a hidden web cam in their room to make sure they aren't doing naughty things like looking at old-media porn or masturbating. Your friend should talk to his kids, not automatically assume their guilt. On Feb 5, 2:57 am, "jack trades" wrote: > I wrote a simple keylogger for a friend of mine that wants to keep track of > his kid's (12 and 14 yr old boys) computer usage to make sure they aren't > getting into the naughty parts of the web. The logger works great (source > attached at bottom) but I ran into some troubles getting it to autorun on > login. > > The method I tried was to add a registry entry using the function below. > def autostartProgram(): > """Registers program with the windows registry to autostart on login""" > os.system(r'reg add HKLM\software\microsoft\windows\currentversion\run /v > logger /t REG_SZ /d C:\keylogger\logger.py') > > This starts the program on login, no problem. However I noticed that after > logging out and back in on my dev (xp pro) machine that "My Network Places" > was gone from my start menu. I restored the registry and tried again. It > happened over and over. I also had problems with Winamp/Media Player after > doing this (grrr I hate Windoze). > > Also I noticed that when you switch users using this method, it shows that > there is 1 program running. While I'm not trying to be stealthy I don't > want the kids poking around in his system (probably destroying it) trying to > find the program that's running. > > How would I SAFELY start the program at login time for a specific user? > I've been reading google about this for the past 5 hours and I'm stuck, > please help. > Note: I thought about registering it as a system service, but wouldn't that > make the program start for any user that logs on? > > Thanks for sparing some time, > Jack Trades > > PS. The source for the logger is below. I'll post the source for the > reader when I'm finished if anyone's interested (I'll also post it to > uselesspython when they're back up). > Note: Currently this program must be stored in a folder named > "C:\keylogger\" (I won't post to uselesspython until I fix this, but it > seems necessary when autostarting the program through the registry.) > > ## Windows Only Script!!! > ############################################################################ > # > ## logger.py | 2008-02-04 | Logs keystrokes and screenshots to disk > ## > ## Copyright (C) 2008, Jack Trades > ## > ## This program is free software: you can redistribute it and/or modify > ## it under the terms of the GNU General Public License as published by > ## the Free Software Foundation, either version 3 of the License, or > ## (at your option) any later version. > ## > ## This program is distributed in the hope that it will be useful, > ## but WITHOUT ANY WARRANTY; without even the implied warranty of > ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the > ## GNU General Public License for more details. > ## > ## You should have received a copy of the GNU General Public License > ## along with this program. If not, see > ## > ## Recent Changes: > ## Added quality setting to grabScreen > ## Wrapped all functions in try/except blocks to silently pass over errors > ## > ## TODO: > ## Write function to send data to secure ftp server in local network > ## Write any errors to a text file > ############################################################################ > # > ## Requires: pyHook, win32all, PIL > > import pyHook > import pythoncom > import ImageGrab > from time import time > from threading import Timer > > ############################################################################ > # > ## Start-Up > ############################################################################ > # > > ## The full path is required when started automatically through windows > registry > ## Need to find a fix to allow relative paths (this way is UGLY!) > folder = 'C:\\keylogger\\' > > filename = folder+'data\\'+str(time()) ## Each program start creates a new > file > skippedKeys = set( (0,) ) > > def offloadData(): > """Every time the program starts it should offload its log file and > screenshots to another computer. """ > pass > > ############################################################################ > # > ## Keylogger > ############################################################################ > # > ## The logger skips over keys defined in the global variable *skippedKeys* > > def writeData(eventWindow, ascii): > """Appends each keystroke to file *filename* as defined at the top""" > try: > eventTime = time() > f = open(filename, 'a') > f.write(str( (ascii, eventTime, eventWindow) )+',') > f.close() > except: > pass > > def onKeyboardEvent(event): > """This function is called by pyHook each time a key is pressed. > It writes the (key,time,window) to the logfile as defined in writeData() > It also skips unnecessary keys (such as shift, ctrl, alt, etc.)""" > try: > eventWindow, ascii = event.WindowName, event.Ascii > if ascii not in skippedKeys: ## skippedKeys is a global > variable > #ascii = chr(ascii) ## uncomment to store chr(ascii) > values > #print ascii ## uncomment to print keys to > screen > writeData(eventWindow, ascii) > return True ## passes the event to other > handlers > except: > return True ## ensures that we pass the key > along > ## even if an error occurs > > ############################################################################ > # > ## Screenshots > ############################################################################ > # > > def grabScreen(imageQuality=20): > """Take a screenshot and save it to the folder screens// with filename > time()""" > try: > img = ImageGrab.grab() > img.save(folder+'screens\\'+str(time())+'.jpg', quality=imageQuality) > except: > pass > > def startScreenshots(delay=3): > """Takes a screenshot every X seconds using grabScreen()""" > try: > grabScreen() > t = Timer(delay, startScreenshots, [delay]) > t.start() > except: > pass > > ############################################################################ > # > ## Main > ############################################################################ > # > > def run(delay=3): > try: > ## Start saving screenshots every X seconds > startScreenshots(delay) > ## Setup a HookManager and bind OnKeyboardEvent to HookManager.KeyDown > hm = pyHook.HookManager() > hm.KeyDown = onKeyboardEvent > hm.HookKeyboard() > ## Pump keys into HookManager | Does this need a try/except ? > try: > pythoncom.PumpMessages() > except: > pass > except: > pass > > if __name__ == '__main__': > try: > run(3) ## Run keylogger with 3 second delay between screenshots > except: > pass From dennis at xardias.net Tue Feb 12 15:35:31 2008 From: dennis at xardias.net (Dennis Kempin) Date: Tue, 12 Feb 2008 21:35:31 +0100 Subject: How to access object attributes given a string In-Reply-To: <54eee77e-d4b7-42e1-ad1d-564096494f6a@d21g2000prf.googlegroups.com> References: <54eee77e-d4b7-42e1-ad1d-564096494f6a@d21g2000prf.googlegroups.com> Message-ID: Santiago Romero schrieb: > Hi... > > I'm trying to guess how to access attributes of an existing object > given the attribute name in a string. I mean: > > class Object: > self.x = 12 > self.y = 20 > self.name = "blah" > > def ChangeAttribute( object, attribute, value ): > # Insert here the code for object.attribute = value > XXXXX have a look a getattr and setattr setattr(object, "name", "value") > > Allowing this kind of calls: > > ChangeAttribute( object, "x", 200 ) > ChangeAttribute( object, "name", "my name" ) > > Thanks. > > PS: I need it for a concrete case in a game scripting language I'm > writing, so that I can call functions like "CHANGE_PLAYER_VALUES( "x", > 100 )". You are using a scripting language.. why not use python directly? You can pass commands from the game console via the exec statement, and have the complete power of python in your game scripts greetings, Dennis From dickinsm at gmail.com Sun Feb 10 21:52:46 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Sun, 10 Feb 2008 18:52:46 -0800 (PST) Subject: Turn off ZeroDivisionError? References: <63d2e7d1-aa26-4ddc-9d12-42ae636104c1@s37g2000prg.googlegroups.com> <13qunlu5nrva731@corp.supernews.com> <13qusltq0v8vt39@corp.supernews.com> <13qv4dh7fpe0e93@corp.supernews.com> Message-ID: On Feb 10, 7:07?pm, Grant Edwards wrote: > On 2008-02-10, Christian Heimes wrote: > >>>> from somemodule import ieee754 > >>>> with ieee754: > > ... ? ?r = a/0 > > ... ? ?print r > > inf > > That would be great. Seriously, in some of my crazier moments I've considered trying to write a PEP on this, so I'm very interested in figuring out exactly what it is that people want. The devil's in the details, but the basic ideas would be: (1) aim for consistent behaviour across platforms in preference to exposing differences between platforms (2) make default arithmetic raise Python exceptions in preference to returning infs and nans. Essentially, ValueError would be raised anywhere that IEEE 754(r) specifies raising the divide-by-zero or invalid signals, and OverflowError would be raised anywhere that IEEE 754(r) specifies raising the overflow signal. The underflow and inexact signals would be ignored. (3) have a thread-local floating-point environment available from Python to make it possible to turn nonstop mode on or off, with the default being off. Possibly make it possible to trap individual flags. Any thoughts on the general directions here? It's far too late to think about this for Python 2.6 or 3.0, but 3.1 might be a possibility. From deets at nospam.web.de Thu Feb 7 12:32:13 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 07 Feb 2008 18:32:13 +0100 Subject: a trick with lists ? In-Reply-To: <47ab3de3$0$9587$426a34cc@news.free.fr> References: <47ab3de3$0$9587$426a34cc@news.free.fr> Message-ID: <610tlcF1t2hegU1@mid.uni-berlin.de> "S??????????????????????????????????????????????" schrieb: > I've found some class on the Net which takes basically this form : > > ###### > class Foo: > def __init__(self): > self.tasks = [] > ... > > def method1(self): > tasks = [] > while True: > ... > append/pop elements into/from tasks > ... > if condition : break > > self.tasks[:] = tasks > return > ###### > > What I do not fully understand is the line "self.tasks[:] = tasks". Why does > the guy who coded this did not write it as "self.tasks = tasks"? What is the > use of the "[:]" trick ? It changes the list in-place. If it has been given to other objects, it might require that. Diez From dickinsm at gmail.com Mon Feb 25 16:52:56 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Mon, 25 Feb 2008 13:52:56 -0800 (PST) Subject: PyEuler References: <9e435ab2-3323-4ad9-9dd9-cdde34c3fb91@e25g2000prg.googlegroups.com> <7x1w70x2hd.fsf@ruckus.brouhaha.com> Message-ID: On Feb 25, 4:24?pm, Arnaud Delobelle wrote: > def genfib(a=0, b=1): > ? ? for a, b in iter(lambda:(b, a+b), None): > ? ? ? ? yield a > > ;-) > > Ahem. ?I admit that somehow, I am proud of this. You're one sick puppy dog. :-) (P.S. Your mother was a hamster, and your father smelt of elderberries.) Gratuitous insulting'ly yours, Mark From gagsl-py2 at yahoo.com.ar Wed Feb 27 20:27:23 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 27 Feb 2008 23:27:23 -0200 Subject: call by reference howto???? References: <47c5f9b8$0$21935$9b4e6d93@newsspool2.arcor-online.net> Message-ID: En Wed, 27 Feb 2008 22:02:19 -0200, Tamer Higazi escribi?: > Can somebody of you make me a sample how to define a function based on > "call by reference" ??? > > I am a python newbie and I am not getting smart how to define functions, > that should modify the variable I passed by reference. First read this article http://effbot.org/zone/python-objects.htm and then this one http://effbot.org/zone/call-by-object.htm There is a FAQ entry at http://www.python.org/doc/faq/programming/#how-do-i-write-a-function-with-output-parameters-call-by-reference The Google interface is good for searching past messages on this topic: http://groups.google.com/group/comp.lang.python/ -- Gabriel Genellina From jeff at schwabcenter.com Fri Feb 22 14:23:27 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Fri, 22 Feb 2008 11:23:27 -0800 Subject: Return value of an assignment statement? In-Reply-To: References: <6d945394-739e-4c47-ad71-faaab8f9d566@34g2000hsz.googlegroups.com> <835a4fc1-f62a-4141-bca4-4e4f52519466@s37g2000prg.googlegroups.com> <5sudnTSXrZY0aCDanZ2dnUVZ_rKtnZ2d@comcast.com> <67ff8198-1d7d-4690-a9b6-42ebab2e642f@p73g2000hsd.googlegroups.com> <5MSdnceVGdH0iCPanZ2dnUVZ_vPinZ2d@comcast.com> <105cfd9f-0c50-4589-8bf6-9e16227dce75@s19g2000prg.googlegroups.com> Message-ID: George Sakkis wrote: > On Feb 22, 12:26 am, Jeff Schwab wrote: > >>> On the other hand, "a = b" does always the same thing; unlike C++, '=' >>> is not an operator and therefore it cannot be overriden by the class >>> of 'a'. >> "Not an operator?" Then what is it? > > In this context, it's just the token used for the assignment > statement. In short, if 'a' is an identifier, the statement means > "bind the name 'a' to the object 'b' (in the local or global > namespace)". It doesn't say anything about memory allocation, > initialization or copying. The only case where assigning an identifier > affects memory is the following [1]: > > """ > The name is rebound if it was already bound. This may cause the > reference count for the object previously bound to the name to reach > zero, causing the object to be deallocated and its destructor (if it > has one) to be called. > """ > > [1] http://docs.python.org/ref/assignment.html OK, thanks for trying to make it clear. I'm about through with this discussion, but FWIW, this is a real gotcha for me and many others. This is a case where Python does not do what many programmers expect, and it at least takes some getting used-to. From mattheww at chiark.greenend.org.uk Sun Feb 24 06:40:53 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 24 Feb 2008 11:40:53 +0000 (GMT) Subject: Article of interest: Python pros/cons for the enterprise References: <4uadnS7kD_jLP13anZ2dnUVZ_tCrnZ2d@comcast.com> Message-ID: Jeff Schwab wrote: > Matthew Woodcraft wrote: >> I see. Then, unless you don't care about data loss passing silently, >> this 'most traditional' way to open a file is unsuitable for files >> opened for writing. > No, why would you think so? If you want something special to happen > when the close() fails (as you indeed would if you were writing > important data), you have to say somehow that you want your special code > called. What syntax would you like to see? Here's what the C++ would > look like, supposing you have a type LoggingCloser that calls close and > logs any failure: Sure, but this LoggingCloser isn't what you described as the 'most traditional, easiest way to open a file in C++'. The more general point is that, where you want to take action on cleanup and you need to handle errors from this action, it usually isn't enough to have one class per type of resource which knows what clean up action is required (because the required response to the error usually varies). Additionally, in languages where exceptions are the usual way to report errors but exceptions from destructors are not managed pleasantly, the error recovery code can't use the language's normal mechanisms for dealing with the error response. -M- From lists at cheimes.de Mon Feb 4 09:50:15 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 04 Feb 2008 15:50:15 +0100 Subject: Too many open files In-Reply-To: <500106b8-447d-41db-a99b-adc5ae00a223@z17g2000hsg.googlegroups.com> References: <47a70bd0$0$3908$426a74cc@news.free.fr> <500106b8-447d-41db-a99b-adc5ae00a223@z17g2000hsg.googlegroups.com> Message-ID: Jeff wrote: > Why don't you start around 50 threads at a time to do the file > writes? Threads are effective for IO. You open the source file, > start a queue, and start sending data sets to be written to the > queue. Your source file processing can go on while the writes are > done in other threads. I'm sorry, but you are totally wrong. Threads are a very bad idea for IO bound operation. Asynchronous event IO is the best answer for any IO bound problem. That is select, poll, epoll, kqueue or IOCP. Christian From arkanes at gmail.com Fri Feb 22 10:56:05 2008 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 22 Feb 2008 09:56:05 -0600 Subject: Article of interest: Python pros/cons for the enterprise In-Reply-To: <9a3f9e3c-acf5-453f-a075-e0a044b21237@p73g2000hsd.googlegroups.com> References: <2f1527a7-2f66-44c7-9665-4d8ff01fa5ab@28g2000hsw.googlegroups.com> <47bd4a24$0$25225$426a74cc@news.free.fr> <036e93e6-5840-4a3c-8642-67a0a9ec44f2@i7g2000prf.googlegroups.com> <784ec210-f389-4a15-b458-961100de9103@v3g2000hsc.googlegroups.com> <9a3f9e3c-acf5-453f-a075-e0a044b21237@p73g2000hsd.googlegroups.com> Message-ID: <4866bea60802220756x59200fcbg68d5721e19819257@mail.gmail.com> On Fri, Feb 22, 2008 at 4:56 AM, Nicola Musatti wrote: > On Feb 22, 12:24 am, Carl Banks wrote: > > On Feb 21, 1:22 pm, Nicola Musatti wrote: > > > > > There are other downsides to garbage collection, as the fact that it > > > makes it harder to implement the Resource Acquisition Is > > > Initialization idiom, due to the lack of deterministic destruction. > > > > That's not a downside: it's at least a wash. > > > > In C++ you manage memory and the language manages resources. In > > Python you manage resources and the language manages memory. > > > > RAII is merely one way of minimizing complexity. Garbage collection > > is another way. > > In C++ memory is just another resource which you can handle just like > any other one, possibly using RAII. GC deals with memory very > reasonably, but makes it more complicate to deal with other resources. > There are many different kinds of resource and they have different optimal handling techniques. Memory in particular is really easily handled by GC - it's a resource that you can reclaim under pressure, so deferring it's collection and release makes sense, and it's even common these days for high quality GC to beat manual management in performance (never mind correctness). Other kinds of resource are much more timely, and require tight control over scopes, like mutexes and other locks. RAII is fantastic for these sort of things. Shared but limited resources like files work best with refcounting (closing a file that something else holds a reference to is usually an error). Optimally, you would have a language that provides all three in easy, transparent ways. Python only provides two, but the first on is the least important so Python manages at least a B. C++ provides all 3, but importantly there's no language level enforcement of use, so you can (and people do, and this is a common source of bugs) accidentally bypass the mechanisms. If I had to use C++ these days, I'd use D instead. From bearophileHUGS at lycos.com Wed Feb 6 03:04:59 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 6 Feb 2008 00:04:59 -0800 (PST) Subject: IronPython vs CPython: faster in 1.6 times? References: <52c34392-5c5b-49b8-8c75-ba9add438b73@k39g2000hsf.googlegroups.com> <47A8BD65.2090707@behnel.de> Message-ID: <08cfdcc7-60e5-4ae7-b18f-0739ed75825d@i7g2000prf.googlegroups.com> Stefan Behnel: > This doesn't look like Mono to me: > IronPython 1.1 (1.1) on .NET 2.0.50727.42 You are right! I think this shows that IronPython isn't faster than CPython at all :-) (And it uses more memory). Bye, bearophile From john106henry at hotmail.com Sat Feb 9 17:53:06 2008 From: john106henry at hotmail.com (John Henry) Date: Sat, 9 Feb 2008 14:53:06 -0800 (PST) Subject: pyinstall and matplotlib Message-ID: <254161cb-f927-4659-b1a5-c34b5c2953ac@s8g2000prg.googlegroups.com> Has anybody been able to create an exe of their python applications involving matplotlib using pyinstall (ver 1.3)? I am getting a: RuntimeError: Could not find the matplotlib data files when I attempt to run the exe created. In searching the web, it appears this is an issue when others tried to use py2exe as well. Unfortunately, the few hits I saw doesn't include enough details to inspire me as to what I should be doing in my pyinstall .spec file. Does anybody has an example or information about this? Thanks, From dickinsm at gmail.com Sun Feb 24 13:21:44 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Sun, 24 Feb 2008 10:21:44 -0800 (PST) Subject: How about adding rational fraction to Python? References: <676ca28c-b471-41c8-8661-fcd2ea8c23f0@i12g2000prf.googlegroups.com> <74b95b3b-1d6a-42a6-b55d-e77a868b1ffe@64g2000hsw.googlegroups.com> <70ecaf16-7308-455f-9048-730b2b2f9f2f@p43g2000hsc.googlegroups.com> <13rf9tvbkt66r2a@corp.supernews.com> <198927a7-9478-42b3-a972-82049f0130ac@u10g2000prn.googlegroups.com> <1bc9bba7-dc7f-4cfe-8e1c-fa5901c9f556@n77g2000hse.googlegroups.com> <97f30679-483d-4751-9a6e-0858b36eb426@d4g2000prg.googlegroups.com> Message-ID: <649ac8a9-ae09-4e9b-85c2-f37043af21fd@28g2000hsw.googlegroups.com> On Feb 24, 1:09?pm, Lie wrote: > And this limit is much lower than n!. I think it's sum(primes(n)), but > I've got no proof for this one yet. It's the least common multiple of the integers 1 through n, or equivalently the product over all primes p <= n of the highest power of p not exceeding n. So for n = 100, it's: 64 * 81 * 25 * 49 * 11 * 13 * 17 * ... rest of primes up to 100. For general n, this number is of roughly the same order of magnitude as e**n. See http://www.research.att.com/~njas/sequences/A003418 for more. Mark From michele.simionato at gmail.com Wed Feb 20 00:10:22 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 19 Feb 2008 21:10:22 -0800 (PST) Subject: Why must implementing Python be hard unlike Scheme? References: Message-ID: <7de938c8-e8ad-4747-ac64-071ae2d2e8d3@z70g2000hsb.googlegroups.com> On Feb 19, 7:15 am, "seber... at spawar.navy.mil" wrote: > I'm learning Scheme and I am amazed how easy it is to start building a > half baked Scheme implementation that somewhat works. This was true for R5RS Scheme, not anymore. Michele Simionato From davidson.kris at gmail.com Wed Feb 27 22:47:26 2008 From: davidson.kris at gmail.com (Kris Davidson) Date: Thu, 28 Feb 2008 03:47:26 +0000 Subject: Python IRC Zork In-Reply-To: References: Message-ID: I should have said, I'm guessing subprocess is the way to go but I'm probably wrong. On 28/02/2008, Kris Davidson wrote: > Hi, > > If this has been done before in another language could someone please > tell me, if not I was wondering is its possible and what the easier > way is to create an IRC bot that allows you to play Zork: > > I was thinking of just creating a simple Python IRC bot or finding an > existing one then have it run Zork and read/write from stdout/stdin. > > Is that possible? Is there a better or easier way to do it? Are there > any existing programs that do something similar? > > Or just really anything else people have to say on the subject. > > Thanks > > > Kris > From miller.paul.w at gmail.com Sun Feb 3 12:51:15 2008 From: miller.paul.w at gmail.com (miller.paul.w at gmail.com) Date: Sun, 3 Feb 2008 09:51:15 -0800 (PST) Subject: Python GUI toolkit References: Message-ID: <7a4ab81f-61bc-4371-938b-73e16edf4e45@c4g2000hsg.googlegroups.com> On Feb 3, 10:18 am, defa... at defaulted.default wrote: > what would be the best python GUI toolkit, it must be cross platform. > > i have tried gtk, but it interface are real bad and its coding was difficult > so i dropped it, > [...] If "cross-platform," and "nice API" are your requirements, I recommend you investigate Tkinter. I find it fairly easy to get my head around, and it's available nearly everywhere Python is. It doesn't even depend on gtk or qt. The widgets are fairly basic, but you can create compound widgets in Python by composing the basic widgets, and there are extensions like Tix and Python Megawidgets that give you more widgets to work with. If you want to see a couple examples of what can be done with Tkinter, take a look at idle (the IDE that comes with most Python distributions), and pysol (a solitaire game written in Python using Tkinter). From bruno.desthuilliers at gmail.com Tue Feb 12 15:41:05 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Tue, 12 Feb 2008 12:41:05 -0800 (PST) Subject: How to access object attributes given a string References: <54eee77e-d4b7-42e1-ad1d-564096494f6a@d21g2000prf.googlegroups.com> Message-ID: On 12 f?v, 21:35, Dennis Kempin wrote: > Santiago Romero schrieb: (snip - others already answered) > > PS: I need it for a concrete case in a game scripting language I'm > > writing, so that I can call functions like "CHANGE_PLAYER_VALUES( "x", > > 100 )". > > You are using a scripting language.. why not use python directly? I can only second this suggestion - FWIW, there are already quite a couple popular (and less popular) games using Python as a scripting language. From bronger at physik.rwth-aachen.de Thu Feb 7 15:31:40 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Thu, 07 Feb 2008 21:31:40 +0100 Subject: Why not a Python compiler? References: <28eead2f-a40c-414b-bd3d-a941f8a851a2@d70g2000hsb.googlegroups.com> <7da40f42-f64f-4939-a0dc-d24d1ff85f2d@v4g2000hsf.googlegroups.com> <13qjktdbe76da00@corp.supernews.com> <13qmp56btnr55a4@corp.supernews.com> Message-ID: <87tzkko6dv.fsf@physik.rwth-aachen.de> Hall?chen! Grant Edwards writes: > On 2008-02-06, Gary Duzan wrote: > >> In article <13qjktdbe76da00 at corp.supernews.com>, >> >> Grant Edwards wrote: >> >>> [...] >>> >>> Ouch. Two demerits for using the distance unit "parsec" in a >>> context where a quantity of time was required. >> >> No demerits for Andrew; it is a Star Wars reference, which is >> quite on topic for this subthread. >> >> http://starwars.wikia.com/wiki/Kessel_Run > > Silly me. > > I wonder if George Lucas intended it as a joke or if he thought > a parsec was a unit of time. The latter because it was corrected in the novelization. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From nick at stinemates.org Mon Feb 18 21:52:21 2008 From: nick at stinemates.org (Nick Stinemates) Date: Mon, 18 Feb 2008 18:52:21 -0800 Subject: name of client module In-Reply-To: References: <2KCdnWJQeaBuuCfanZ2dnUVZ_sednZ2d@comcast.com> Message-ID: <47BA4465.6040709@stinemates.org> > I'm not saying I don't want to do that. I'm saying that, in addition to > what you've written, I want foo to know it's being imported, and by whom. > You're still not explaining a real example of what this could be used for. Oh well, here's an example of an implementation of what you want to do. Import.py ================ #!/usr/bin/python class Importer: def __init__(self): pass def __import__(self, module): exec "import %s" % module exec "a = %s" % module a.setImported(self) i = Importer() i.__import__("Imported") ================ Imported.py ================ #!/usr/bin/python def setImported(importer): print "I've been imported by %s" %importer ================ -- ================== Nick Stinemates (nick at stinemates.org) http://nick.stinemates.org AIM: Nick Stinemates MSN: nickstinemates at hotmail.com Yahoo: nickstinemates at yahoo.com ================== From arnodel at googlemail.com Mon Feb 25 17:47:20 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 25 Feb 2008 14:47:20 -0800 (PST) Subject: PyEuler References: <9e435ab2-3323-4ad9-9dd9-cdde34c3fb91@e25g2000prg.googlegroups.com> <7x1w70x2hd.fsf@ruckus.brouhaha.com> <0a552b42-69f0-492f-9357-38ad5226c4ed@d4g2000prg.googlegroups.com> Message-ID: On Feb 25, 10:25?pm, bearophileH... at lycos.com wrote: > Paul Rubin: > > > ? ? def ggenfib(): > > ? ? ? a,b = 1,2 > > ? ? ? while True: > > ? ? ? ? ?yield a > > ? ? ? ? ?a,b = b, a=b > > Your version is the nice basic generator version (the last line > contains a +, I presume), but I like this other version too: > > def xfibonacci(): > ? ? a = b = 1 > ? ? yield a > ? ? yield b > ? ? while True: > ? ? ? ? a = a + b > ? ? ? ? yield a > ? ? ? ? b = b + a > ? ? ? ? yield b > > It's a bit faster, longer, and I find it a bit more readable. In this case why not: def xfib(a=1, b=1): while True: yield a a += b yield b b += a -- Arnaud From gagsl-py2 at yahoo.com.ar Tue Feb 5 12:06:59 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 05 Feb 2008 15:06:59 -0200 Subject: extending python with array functions References: <47a7793b$0$85781$e4fe514c@news.xs4all.nl> <60qhh1F1s5jpaU7@mid.uni-berlin.de> Message-ID: En Tue, 05 Feb 2008 05:28:33 -0200, Marc 'BlackJack' Rintsch escribi?: > On Mon, 04 Feb 2008 20:56:02 -0200, Gabriel Genellina wrote: > >> - the array module http://docs.python.org/lib/module-array.html provides >> homogeneuos arrays that may be more efficient for your application. >> arrays >> don't have a special API, you have to import the module and use its >> functions the same as one would do in pure Python. > > There's one special thing about it: the `buffer_info()` method returns a > tuple with the memory address and length (in items) of the current > underlying buffer. Pretty useless information in Python but handy in > extensions that can directly access the "raw" memory. Good to know! I didn't notice it the (only) time I had to use arrays from C code. -- Gabriel Genellina From Graham.Dumpleton at gmail.com Mon Feb 4 17:43:33 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Mon, 4 Feb 2008 14:43:33 -0800 (PST) Subject: Problem with Image: Opening a file References: <8f26f164-2b71-422d-baf7-70ba9a68b3b8@e10g2000prf.googlegroups.com> Message-ID: <508752cc-c22b-433a-bdac-21fc8a829800@q77g2000hsh.googlegroups.com> On Feb 4, 6:51 pm, mcl wrote: > I am obviously doing something stupid or not understanding the > difference between HTML file references and python script file > references. > > I am trying to create a thumbnail of an existing .jpg file. It is in > the directory 'temp', which is below my script > > I can display the file with , but Image.open does not see it. > > I think it is probably a path problem, but I have tried '/temp/ > fred.jpg' and './temp/fred.jpg' > > Can anyone help, please > > PS I am usingmod_pythonon a Linux Apache 2 and python 2.5 > > CODE ================================================= > > import os > import StringIO > > def index(req): > main(req) > > def writeHTMLHeader(req): > > req.content_type = "text/html" > req.write(' EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">') > req.write(' xml:lang="en">') > req.write('My Tests: Python') > req.write('') > > def writeHTMLTrailer(req): > req.write('') > req.write('') > > def writelineHTML(req, htmlMSG): > req.write(htmlMSG + '
\n') > > def createThumb(req, infile, maxwidth, maxheight): > import Image > import os > infile = "temp/fred.jpg" > outfile = "temp/fred_th.jpg" > if infile != outfile: > > writelineHTML(req, "Opening %s" % str(infile)) > writelineHTML(req, '' % infile) # Finds > File OK *********************** > im = > Image.open(infile) # > ERRORS on the same file ********************* > im.thumbnail((maxwidth,maxheight),Image.ANTIALIAS) > im.save(outfile, "JPEG") > writelineHTML(req, "Created: " + str(outfile)) > writelineHTML(req, '' % outfile) > > return outfile > > return "" > > def showThumbnail(req, picture): > myThumb = createThumb(req, picture, 60, 60) > if myThumb: > writelineHTML(req, ' > def main(req): > writeHTMLHeader(req) > picture = "temp/fred.jpg" > showThumbnail(req, picture) > writeHTMLTrailer(req) > > ERROR ============================================== > > File "/home/mcl/htdocs/timslists/thumbs2.py", line 33, in > createThumb > im = Image.open(infile) > > File "/usr/lib/python2.5/site-packages/PIL/Image.py", line 1888, in > open > fp = __builtin__.open(fp, "rb") > > IOError: [Errno 2] No such file or directory: 'temp/fred.jpg' > > Richard Code under mod_python will typically run as Apache user. This means that when writing files the location you use must be writable to the Apache user. Do note though that the working directory of Apache is not guaranteed and you must always use an absolute path to the location you are saving files, you cannot reliably use relative paths like you are. BTW, do you perhaps mean '/tmp/fred.jpg'? There is no '/temp' directory on Linux boxes. Graham From fomcl at yahoo.com Fri Feb 15 06:11:24 2008 From: fomcl at yahoo.com (Albert-jan Roskam) Date: Fri, 15 Feb 2008 03:11:24 -0800 (PST) Subject: newbie question: converting csv to another dialect Message-ID: <987622.53552.qm@web32710.mail.mud.yahoo.com> Hi all, I have a csv file with tab as a delimiter. I want to convert it into one that is comma delimited. I changed the regional settings on my computer to US. At first I thought I could use the CSV module for this, by reading the csv file, registering the new (desired = comma-delimited) dialect, and writing it. Another option (which may be easier) I tried was: f = open('d:/temp/myfile.csv', ' rw') for row in f: row.replace("\t",",") Which is a start, but doesn't do the entire job. Could somebody help me with this please? Thanks very much in advance! Albert-Jan ____________________________________________________________________________________ Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ From gcmartijn at gmail.com Mon Feb 25 15:10:27 2008 From: gcmartijn at gmail.com (gcmartijn at gmail.com) Date: Mon, 25 Feb 2008 12:10:27 -0800 (PST) Subject: bin2chr("01110011") # = 15 function ? Message-ID: <3e9b867e-90bc-465c-bbe9-423f64cfbb29@j28g2000hsj.googlegroups.com> H! I'm searching for a simple bin2chr("01110011") function that can convert all my 8bit data to a chr so I can use something like this: def bin(i): l = ['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111'] s = ''.join(map(lambda x, l=l: l[int(x, 16)], hex(i)[2:])) if s[0] == '1' and i > 0: s = '0000' + s return s print ord("s") # = 115 print bin(ord("s")) # = 01110011 test= open('output.ext,'wb') test.write(bin2chr("01110011")) test.write(bin2chr("01111011")) test.write(bin2chr("01110111")) test.close() I think this is very easy but I'm not very good in python. In a other program I use I do something like this Function bin2int(b$) blen=Len(b) For f=1 To blen n=n Shl 1 + (Mid(b,f,1)="1") Next Return n End Function From dblubaugh at belcan.com Fri Feb 15 17:13:24 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Fri, 15 Feb 2008 17:13:24 -0500 Subject: scary thought for consideration Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F38026E5A52@AWMAIL04.belcan.com> To All, I am wondering as far as the integration of MyHDL with Python 2.5, if there might be any potential version incompatibility issues? What I mean is will MyHDL not operate correctly, if it is executed with a Python 2.5 version not a Python 2.4? I will be testing to see if this possibility is indeed true over the weekend. Thanks, David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From newsuser at stacom-software.de Wed Feb 13 10:38:15 2008 From: newsuser at stacom-software.de (Alexander Eisenhuth) Date: Wed, 13 Feb 2008 16:38:15 +0100 Subject: boost.python Event object wrapped with bp::object() Message-ID: Hello everybody, I Use a C++ thread that is called from the python sides to provoke some activities. The calls set some booleans in the thread object and return. To synchrThreadClassonize the execution in the thread, the idea of me is, to give a Python Event() object as bp::object to the C++ thread, that calls the python "set" attribute after the related activity has finished. Maybe this code is clearer: Python: thread = wrapper.ThreadClass() event = Event() thread.methode(event) event.wait() C++: ThreadClass::methode(bp::object event) { this->myEvent = event ... methodeCalled = true ... } ThreadClass::threadLoop() { ... if (methodeCalled) { ... this->myEvent.attr("set")(); } } The application crashes. If I comment out event.wait() it doesn't crash. Any suggestions or experiances? Thanks a lot Alexander From xkenneth at gmail.com Tue Feb 5 22:40:42 2008 From: xkenneth at gmail.com (xkenneth) Date: Tue, 5 Feb 2008 19:40:42 -0800 (PST) Subject: What is the most simple, quicket, yet most powerful python Web-Framework? References: <5d022604-289d-4d4c-bd9a-286435cf77a6@d21g2000prf.googlegroups.com> Message-ID: <462c3828-5451-40a7-aed7-eaea1f333e97@e6g2000prf.googlegroups.com> On Feb 5, 9:33 pm, xkenneth wrote: > > My question is: "What makes you think that there is a royal road to web > > development?" > > I don't, I was just hoping there was something I was missing, or more > simple than anything I'd experienced. > > > > > You have already chosen some technology (Ajax and ZODB) without any > > apparent justification. > > I've chosen Ajax for it's asynchronous nature. Alot of the data I'm > going to be displayed needs to be updated immediately as it comes in. > I've chosen ZODB because of the way it operates. I really enjoy the > flexibility of an object-oriented database as well as the ZEO server, > which will allow me to exactly what I need to do. > > Why not just consult your prejudices for the> others as well. > > I haven't made any decisions as to the technology I'm going to use > with prejudice, I simply failed to explain properly why I chose those > technologies. > > > Come to that, why is it even necessary to select a > > Python-based solution? > > Most of my codebase is currently in python. I use python to do things > like data acquisiton and signal processing. I'm very familiar with > python, and I enjoy developing in it. Python has the technologies > available to it that allow to do what I want to do. > > By the way, thanks to all who replied! > > > I could say "Django can do everything you need from your description of > > your requirements", but then you'd be disappointed that it does in fact > > take time to learn how to do things in Django. Just like it does in any > > other complex framework. > Thanks. > > > regards > > Steve > > -- > > Steve Holden +1 571 484 6266 +1 800 494 3119 > > Holden Web LLC http://www.holdenweb.com/ > > Regards, > Kenneth Miller From kpdere at derenet.us Sat Feb 2 12:52:07 2008 From: kpdere at derenet.us (Ken Dere) Date: Sat, 02 Feb 2008 12:52:07 -0500 Subject: Will Python on day replace MATLAB????????????????????????????????????????????????????? References: Message-ID: <93b4$47a4acc2$47f6d32a$9371@news.flashnewsgroups.com> Blubaugh, David A. wrote: > To All, > > > I have been evaluating the python environment ever more closer. I > believe I can interface python with a development environment known as > the ImpulseC environment. The ImpulseC environment develops C to VHDL > for FPGA development. I would especially love to interface Python > with ImpulseC and the graphing capabilities of GNU Plot and SciPy in > order to recreate a VHDL development environment that will be just as > capable as a $50,000 dollar Matlab to VHDL toolbox. This is also a part > of my Masters thesis. Is anyone willing to help in this endeavor????? > > > David Blubaugh > > > > > > > > -----Original Message----- > From: python-list-bounces+dblubaugh=belcan.com at python.org > [mailto:python-list-bounces+dblubaugh=belcan.com at python.org] On Behalf > Of python-list-request at python.org > Sent: Thursday, January 31, 2008 1:06 PM > To: python-list at python.org > Subject: Python-list Digest, Vol 52, Issue 448 > > Send Python-list mailing list submissions to > python-list at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/python-list > or, via email, send a message with subject or body 'help' to > python-list-request at python.org > > You can reach the person managing the list at > python-list-owner at python.org > > When replying, please edit your Subject line so it is more specific than > "Re: Contents of Python-list digest..." > > This e-mail transmission contains information that is confidential and may > be privileged. It is intended only for the addressee(s) named above. If > you receive this e-mail in error, please do not read, copy or disseminate > it in any manner. If you are not the intended recipient, any disclosure, > copying, distribution or use of the contents of this information is > prohibited. Please reply to the message immediately by informing the > sender that the message was misdirected. After replying, please erase it > from your computer system. Your assistance in correcting this error is > appreciated. Never used Matlab but I did use IDL (also commercial) a lot. However, I recently switched almost entirely to python with the help of numpy, scipy, matplotlib, and ipython for the interactive shell. As far as I am concerned, that day has come and gone. Ken D. From Martin.vonLoewis at hpi.uni-potsdam.de Fri Feb 22 15:16:11 2008 From: Martin.vonLoewis at hpi.uni-potsdam.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 22 Feb 2008 21:16:11 +0100 Subject: [ANN] Python 2.5.2 released Message-ID: <47BF2D8B.50204@hpi.uni-potsdam.de> On behalf of the Python development team and the Python community, I'm happy to announce the release of Python 2.5.2 (FINAL). This is the second bugfix release of Python 2.5. Python 2.5 is now in bugfix-only mode; no new features are being added. According to the release notes, over 100 bugs and patches have been addressed since Python 2.5.1, many of them improving the stability of the interpreter, and improving its portability. This is a production release of Python, and should be a painless upgrade from 2.5.1 or 2.5. Since the release candidate, we have backed out test cases that were incorrect on 64-bit systems, and fixed another stability problem. See the release notes for more. For more information on Python 2.5.2, including download links for various platforms, release notes, and known issues, please see: http://www.python.org/2.5.2/ Highlights of this new release include: Bug fixes. According to the release notes, at least 100 have been fixed. Highlights of the previous major Python release (2.5) are available from the Python 2.5 page, at http://www.python.org/2.5/highlights.html Enjoy this release, Martin Martin v. Loewis martin at v.loewis.de Python Release Manager (on behalf of the entire python-dev team) From kyosohma at gmail.com Tue Feb 5 13:41:15 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 5 Feb 2008 10:41:15 -0800 (PST) Subject: Removing the Close, Min, Maximize and frame with ANY gui toolkit References: Message-ID: On Feb 5, 11:17 am, Daniel Folkes wrote: > I was wondering if anyone knew how to remove the Minimize, Maximize > and Close from the frame around a gui. > Removing everything would work even better. > > I would prefer instructions for tkinter, but any GUI would > suffice(glade, gtk, wx, Qt). I really would like to make a widget > like object instead of a window. > > Thanks, > Daniel Folkeshttp://danfolkes.com I've only ever dabbled with Tkinter, so I'm not sure what its syntax is. However, with wxPython, it's fairly trivial: import wx class MyPopup(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, wx.ID_ANY, 'Test Frame', #size=(450,295), style=wx.STAY_ON_TOP # forces the window to be on top / non-modal ##|wx.DEFAULT_FRAME_STYLE # enable this to get the min/max/close buttons ## |wx.CLOSE_BOX |wx.CAPTION |wx.RESIZE_BORDER) btn = wx.Button(self, wx.ID_ANY, 'Close') self.Bind(wx.EVT_BUTTON, self.close, btn) # display the frame self.Show() def close(self, event): self.Close(True) if __name__ == '__main__': app = wx.PySimpleApp() MyPopup() app.MainLoop() I included a close button as it can be a pain to close these suckers when you disable the default buttons. I read in the last week or two that there's some Linux variant out there that will display the minimize button regardless. If all you want is a non-modal dialog, you might look at the wx.Dialog widget or one of the popup widgets. There's also a Toaster widget... I found this link about Tkinter: http://mail.python.org/pipermail/python-list/2002-July/153111.html Hope that helps you. Mike From gagsl-py2 at yahoo.com.ar Tue Feb 12 19:29:30 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 12 Feb 2008 22:29:30 -0200 Subject: How to broad cast ping address....... References: Message-ID: En Mon, 11 Feb 2008 23:26:14 -0200, Steve Holden escribi?: > Gabriel Genellina wrote: >> En Mon, 11 Feb 2008 13:31:56 -0200, Manikandan R >> escribi?: >> >>> I am working in Python scripting. I an need to find out all the >>> device >>> connected in the network. Just I planned to broad cast the ping address >> >> The simplest approach is to enumerate and ping each and every address in >> your subnet and wait for the response, but consider that some hosts may >> have been configured to not answer (and assuming you don't have a /8 >> network...) >> There is an ICMP library in the Python cookbook >> > Don't I remember Microsoft withdrawing access to the raw packet driver > on Windows XP, or was thing something they decided to ruin in Vaster? Uh, yes, raw sockets are crippled on XP SP2. There is always subprocess.call("ping ...") - not very nice, of course -- Gabriel Genellina From miller.paul.w at gmail.com Sun Feb 3 12:25:29 2008 From: miller.paul.w at gmail.com (miller.paul.w at gmail.com) Date: Sun, 3 Feb 2008 09:25:29 -0800 (PST) Subject: Does anyone else use this little idiom? References: <07c7918f-e98b-4bfa-bbcc-0aea50355419@s19g2000prg.googlegroups.com> Message-ID: <70996227-4f97-4e19-a0b9-105d641e5ce3@k39g2000hsf.googlegroups.com> On Feb 3, 10:42 am, Zentrader wrote: > > Not to me. If I read "for _ in ...", I wouldn't be quite sure what _ was. > > Is it some magic piece of syntax I've forgotten about? Or something new > > added to language while I wasn't paying attention (I still consider most > > stuff added since 1.5 to be new-fangled :-)). > > +1 to forgotten about > +1 to new-fangled=added since 1.5 When 3000 comes out I'll have to > break down and buy a new Python book. Also, it's amazing how much > posting space is spent here replying to someone who is too lazy to key > in a variable name. Damn! Lol. It isn't that I'm too lazy; it's just that the character "_" looks like "-" to me, and, in the math class I'm taking right now (category theory), "-" is one of the notations to indicate "whatever" -- a metasyntactic placeholder, if you will. (For example, Hom (C, -) is the covariant hom functor from C -> Sets. If this makes no sense to you, don't worry about it.) After this discussion, it seems that if I'm to write Python for public consumption, I should prefer for dummy in xrange (n): do_stuff() or one of the other suggestions instead. :-) From jr9445 at ATT.COM Fri Feb 15 13:09:37 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Fri, 15 Feb 2008 12:09:37 -0600 Subject: Solve a Debate In-Reply-To: References: Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of nexes > Sent: Friday, February 15, 2008 11:25 AM > To: python-list at python.org > Subject: Solve a Debate > > Alright so me and my friend are having argument. > > Ok the problem we had been asked a while back, to do a programming > > He declared an array and assigned the number of days in a month to its > own element in an array. Now > I realise that in this example it would not make a difference in terms > of efficiency, but it is my belief that if > there is more data that needed to be assigned(i.e. a couple megs of > data) it would be simpler (and more efficient) to > do a compare rather then assigning all that data to an array, since > you are only going to be using 1 value and the rest > of the data in the array is useless. > > What are everyone else's thoughts on this? Efficient how? Looking up the data in a array would probably be faster (look-up tables normally are.) You could make the array efficient by using pointers, gaining both space and time efficiency. Mon[1] and mon[3] ... would point to 31. The array can also just be collection of pointers to the multi-megabyte objects on disk. Most languages have modules letting you maintain an index in memory that points to data on disk. If the array is static or otherwise only loaded once into memory at startup, and you have plenty of memory and patience, then who cares if it is inefficient? Simple solutions are normally faster to implement. It's not often that you need to spend three days to save three seconds. Then there's debug and change efficiency. An array lookup is simple to understand and thus less prone to bugs. It can also be easier to change a single array element than to change a complicated formula or a cluster of nested if-then-else statements. ***** The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA625 From duncan.booth at invalid.invalid Mon Feb 25 09:56:02 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 25 Feb 2008 14:56:02 GMT Subject: Array of functions, Pythonically References: <44f265a4-4e8c-4473-9ba8-62fa3b4ed0e4@i7g2000prf.googlegroups.com> Message-ID: MartinRinehart at gmail.com wrote: > My parser has found an expression of the form CONSTANT_INTEGER > OPERATOR CONSTANT_INTEGER. I want to fold this into a single > CONSTANT_INTEGER. > > The OPERATOR token has an intValue attribute, '+' == 0, '-'== 1, etc. > In C I'd put functions Add, Subtract, ... into an array and call > ArithmeticFunctions[ intValue ] to perform the operation. Would I > index into a list of functions in Python, or would IF/ELIF/ELIF ... be > the way to go? > Well, you could add another attribute to the OPERATOR token: token.operation = operator.add or you could have an a list of operations keyed in token.intValue: [ operator.add, operator.sub, ...] or you could use a dictionary (that intValue attribute is just so C): { '+': operator.add, '-': operator.sub, ... } I don't know the structure of your program, but I'd go for subclassing your operator. So you would have classes OperatorAdd, OperatorSub, etc. and then you can make the operation a method of the class. Seomthing like: class Token(object): ... def foldConstants(self): pass class Operator(Token): ... def foldConstants(self): self.left.foldConstants() self.right.foldConstants() if self.left.isConstant and self.right.isConstant: self.value, self.isConstant = self.doFold() class OperatorAdd(Operator): ... def doFold(self): return self.left.value + self.right.value, True From ggpolo at gmail.com Wed Feb 13 15:35:26 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 13 Feb 2008 18:35:26 -0200 Subject: Write ooxml .ods (spreadsheat) from python? In-Reply-To: References: Message-ID: 2008/2/13, Neal Becker : > Guilherme Polo wrote: > > > 2008/2/13, Neal Becker : > >> I'd like to output some data directly in .ods format. > > > > Do you want to output data from .ods file or do you want to input data > > into an ods ? > > > >> This format appears > >> to be quite complex. Is there any python software available to do this? > >> I > >> did look at pyuno briefly. It looks pretty complicated also, and it > >> looks like it uses it's own private version of python, which would not > >> help me. > >> > >> > > > > It is not that complex, it is a zip with several files (the most > > interesting are xml files). It gets a bit hard depending on what you > > want to do exactly, that would include answering the question above. > > > > > I want to write a new ods with my data generated by python. Any hints? > Generate an empty .ods so you get the structure of the zip contents. Then next you generate an .ods with some data so you can see how it saves the content in contents.xml, based on this file you generate a contents.xml for your data. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From bbxx789_05ss at yahoo.com Sun Feb 24 01:49:35 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Sat, 23 Feb 2008 22:49:35 -0800 (PST) Subject: Seeing "locals()" from imported function References: <9fbdbc65-1c3e-4591-8113-d0cba502c08f@p73g2000hsd.googlegroups.com> Message-ID: On Feb 23, 11:41?pm, 7stud wrote: > On Feb 23, 10:06?pm, "Luis M. Gonz?lez" wrote: > > > > > I apologize for this very basic question, but I can't understand how > > this works... > > I want to import a function from module B into my main script A, so > > this function can see and use the locals from A. > > > For example: > > > def auto(): > > ? ? urls = ['/', 'index'] > > ? ? for k,v in __main__.locals().items(): ? ? ? ? # ?these "locals" > > are the ones of the main script > > ? ? ? ? ? ? if isinstance(v,type) and k != 'index': > > ? ? ? ? ? ? ? ? ? ? urls.append('/%s' %k) > > ? ? ? ? ? ? ? ? ? ? urls.append(k) > > ? ? return tuple(urls) > > > Of course this doesn't work... > > > Any hint? > > Yes, define your functions so that they get all the input they need > from the arguments that are passed in. For instance: #file1.py: def auto(a_list): for elmt in a_list: print elmt #file2.py: import file1 file1.auto(whatever) From nure123 at gmail.com Thu Feb 28 11:42:59 2008 From: nure123 at gmail.com (nure123 at gmail.com) Date: Thu, 28 Feb 2008 08:42:59 -0800 (PST) Subject: TypeError: only length-1 arrays can be converted to Python scalars. Message-ID: <77b4b412-5588-445e-8eee-1917b4bb6be8@p43g2000hsc.googlegroups.com> Hi All, Could anybody tell me what is the problem with the following sequence with which I always get the above error message. I use Numeric and Python 2.4 x=array([1,2,3,4]) y=exp(x) Nure From bbxx789_05ss at yahoo.com Mon Feb 18 15:58:58 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 18 Feb 2008 12:58:58 -0800 (PST) Subject: average of PIL images References: Message-ID: On Feb 18, 10:18?am, vaneric wrote: > hi > i have a set of RGB images of diff faces (of people )as a 2 dim > numpyarray > ..something like > threefaces=array([[xa1,xa2,xa3], > ? ? ? ?[xb1,xb2,xb3], > ? ? ? ?[xc1,xc2,xc3]]) > where xa1,xa2,xa3 are ?tuples each representing rgb values of a pixel > of first image .. > > i need to create the average face image and display it.problem is i > need to calculate (xa1+xb1+xc1)/3 ?etc to calculate avearge value of > each pixel.how can i do this calculation.do i need to convert the > r,g,b in to a single value for each pixel? the average value of a > pixel will be a float isn't it? how can i create a PIL image from > this? > any help,directive greatly appreciated > eric import Numeric arr = Numeric.array([ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ]) col1 = arr[0:,0] print col1 sum = 0 count = 0 for num in col1: sum += num count += 1 avg = (sum * 1.0)/count #convert one term to a float to get float result print avg print round(avg) print int(round(avg)) print arr[0] size = len(arr[0]) for i in range(size): col = arr[0:, i] sum = 0 count = 0 for num in col: sum += num count += 1 result = (sum * 1.0) /count print result, result = int(round(result)) print result --output:-- [ 1 4 7 10] 5.5 6.0 6 [1 2 3] 5.5 6 6.5 7 7.5 8 From steve at holdenweb.com Sun Feb 3 13:02:23 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 03 Feb 2008 13:02:23 -0500 Subject: interested???? In-Reply-To: <95237c1a-49f2-49fd-9869-81f662e8cb3e@l32g2000hse.googlegroups.com> References: <95237c1a-49f2-49fd-9869-81f662e8cb3e@l32g2000hse.googlegroups.com> Message-ID: no -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From BjornSteinarFjeldPettersen at gmail.com Mon Feb 25 18:59:14 2008 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Mon, 25 Feb 2008 15:59:14 -0800 (PST) Subject: Hyphenation module PyHyphen-0.3 released References: <47c07478$0$26904$6e1ede2f@read.cnntp.org> <9c37ed98-907d-4102-96b2-78867cd351e2@o10g2000hsf.googlegroups.com> <9d9c5dc0-ff54-4355-8c7f-fe35b04ccf74@p43g2000hsc.googlegroups.com> Message-ID: <51280e26-df18-4aca-ab1e-3feef975da93@s37g2000prg.googlegroups.com> On Feb 25, 3:56 am, Ivan Illarionov wrote: > > I don't know if I'm just doing it wrong, or if I can't use extensions > > compiled with mingw32 with the standard distribution Python > > executable? > > I was able to install on Windows XP with mingw: > > setup.py build -c mingw32 > setup.py install --skip-build > > It works fine with English dictionary, but hangs with Russian > dictionary from Mozilla. This is unfortunately deceptive :-( The C-runtime mismatch problem happens when memory malloc'd in an extension module is free'd by the interpreter (or vice versa). Things might work for a while with this mismatch, but will (almost) always crash/hang/etc. in hard to track down ways later. Using the link that max provided above, I managed to build and install without passing any switches and getting no error messages. -- bjorn From yt.rabb at gmail.com Thu Feb 28 18:09:30 2008 From: yt.rabb at gmail.com (John Earls) Date: Thu, 28 Feb 2008 15:09:30 -0800 (PST) Subject: Windows gzip problem Message-ID: Hello, I am having a problem with gzip. The code worked fine under linux but when I moved it over to windows it is getting stuck unzipping a gz file. -- snippet -- fileObj = gzip.GzipFile(iceGetter.file.localFileName, 'rb') uncompressedFileName = iceGetter.file.localFileName[:-3] output = open(uncompressedFileName, 'wb') output.write(fileObj.read()) output.close() fileObj.close() -- snippet -- typing "python autoIce.py" gets this error: --error-- Traceback(most recent call last): File "runAuto.py", line 17 in ? output.write(fileObj.read()) File "C:\Python24\lib\gzip.py". line 217 in read self._read(readsize) File "C:\Python24\lib\gzip.py", line 276 in _read uncompress.decompress.decompress(buf) Memory Error --end error-- I tried playing around with the wb/rb when writing and unzipping, like this post [http://groups.google.com/group/comp.lang.python/ browse_thread/thread/96651e3cd2dc6070/e94ae3b22fc78a1b?lnk=gst&q=gzip +windows#e94ae3b22fc78a1b] suggested and that did not seem to change anything. I would really appreciate any assistance on this. Thanks John From luismgz at gmail.com Tue Feb 5 18:19:43 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M._Gonz=E1lez?=) Date: Tue, 5 Feb 2008 15:19:43 -0800 (PST) Subject: IronPython vs CPython: faster in 1.6 times? References: <52c34392-5c5b-49b8-8c75-ba9add438b73@k39g2000hsf.googlegroups.com> Message-ID: On 5 feb, 14:31, dmitrey wrote: > Hi all, > the urlhttp://torquedev.blogspot.com/2008/02/changes-in-air.html > (blog of a game developers) > says IronPython is faster than CPython in 1.6 times. > Is it really true? > If yes, what are IronPython drawbacks vs CPython? > And is it possible to use IronPython in Linux? > > D. I posted a little benchmark some time ago in ironpython's list that showed a big performance gap between both implementations (being cpython much faster than ironpython). Jim Hugunin replied showing that making the script more abstract (encapsulating code as much as possible into functions) the .NET framework makes a better job at optimizing everything. So I took Istvan script and made a little modification as follows: import time def foo(a): return a * a def do(): start = time.time() data = {} for i in xrange( 10**6 ): data[i] = foo(i) print 'Elapsed time:%5.2f s' % ( time.time() - start) do() # pre-run to avoid initialization time do() import psyco psyco.full() print '\nNow with psyco...\n' do() do() input() The result is that it runs slighty faster in both, IP and CP, but cpython is still faster (around 2x) than ironpython. However, when using psyco simply blows everything out of the water... These are my results. Ironpython 2.0 Alpha 8: Elapsed time: 3.14 s Elapsed time: 3.36 s cpyhon 2.5: Elapsed time: 1.55 s Elapsed time: 1.58 s Now with psyco... Elapsed time: 0.88 s Elapsed time: 0.80 s From frank at niessink.com Mon Feb 11 15:37:31 2008 From: frank at niessink.com (Frank Niessink) Date: Mon, 11 Feb 2008 21:37:31 +0100 Subject: Topographical sorting In-Reply-To: <9c2b11780802102110k1b3ba900s7b549ea41c42c78b@mail.gmail.com> References: <9c2b11780802102110k1b3ba900s7b549ea41c42c78b@mail.gmail.com> Message-ID: <67dd1f930802111237l549dd7acua855dfb09538d0ad@mail.gmail.com> Hi John, 2008/2/11, John : > Now, on to my problem. Topographical sorting essentially involves removing > the minimal element in a set (1), and then arbitrarily choosing the next > minimal element and removing it as well. So, after removing 1, one could > remove 5, then 2, then 3, then 4, then 6, resulting in the sort of 15234. > One could also get 123456. There are a number of sorts possible. This is > where I am currently stuck, attempting to implement an algorithm that finds > all possible sorts. I have looked at the topographical pseudocode available > at Wikipedia, but this does not apply - it finds one topographical sort, not > all. How about something like this: def allSorts(set): result = [] for element in smallestElements(set): for tail in allSorts(set - element): result.append([element] + tail) return result Cheers, Frank From george.sakkis at gmail.com Sat Feb 16 12:26:21 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sat, 16 Feb 2008 09:26:21 -0800 (PST) Subject: TRAC - Trac, Project Leads, Python, and Mr. Noah Kantrowitz (sanitizer) References: <3d40196b-b1c8-4e18-92f0-7ce5a5a38853@u72g2000hsf.googlegroups.com> Message-ID: On Feb 16, 12:15 pm, Jeff Schwab wrote: > Ilias Lazaridis wrote: > > Essence: > > Spam spam spam spam... > > I just looked at your resume. What is Abstract Project Management? A branch of Analysis Paralysis Vaporware. From steve at holdenweb.com Fri Feb 15 14:40:14 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 15 Feb 2008 14:40:14 -0500 Subject: [OT] Looking for a Python Program/Tool That Will Add Line Numbers to a txt File In-Reply-To: <0T1tj.8783$0o7.429@newssvr13.news.prodigy.net> References: <4BRsj.10199$Ch6.5665@newssvr11.news.prodigy.net> <0T1tj.8783$0o7.429@newssvr13.news.prodigy.net> Message-ID: I'll see your IBM 650 and raise you a Univac 418 with a FastRand drum. regards Steve W. Watson wrote: > Good grief! You go a long way back. Want to try for an IBM 650 with a drum > memory? > > Gabriel Genellina wrote: >> En Thu, 14 Feb 2008 04:54:56 -0200, W. Watson >> escribi?: >> >>> See Subject. It's a simple txt file, each line is a Python stmt, but I >>> need >>> up to four digits added to each line with a space between the number >>> field >>> and the text. Perhaps someone has already done this or there's a >>> source on >>> the web for it. I'm not yet into files with Python. A sudden need has >>> burst >>> upon me. I'm using Win XP. >> This command should suffice - but you must first find a working CP/M >> system to use it: >> >> C>PIP [N] NEW.PY=OLD.PY >> >> (Sorry - just a a nostalgic flash!) >> > -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From tjreedy at udel.edu Thu Feb 28 16:18:25 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 28 Feb 2008 16:18:25 -0500 Subject: Indentation and optional delimiters References: <555b548f-1296-4374-b6ce-65691d1dbb7f@s8g2000prg.googlegroups.com><13s92u3sibaus4f@corp.supernews.com><3f55d3b1-c32c-42bc-bd4b-52e2725049b0@v3g2000hsc.googlegroups.com><13scm5m9jmdns02@corp.supernews.com> <318b03dc-4cc5-49de-aeb9-e1b6e590007f@u10g2000prn.googlegroups.com> Message-ID: wrote in message news:318b03dc-4cc5-49de-aeb9-e1b6e590007f at u10g2000prn.googlegroups.com... | But the default behavior may become the "true" copy, that seems | simpler for a newbie to grasp. To me, it is the opposite. If I say gvr = Guido_van_Russum # or any natural language equivalent do you really think a copy is made? Copying is much more work than defining an alias or nickname. From grflanagan at gmail.com Wed Feb 27 11:08:20 2008 From: grflanagan at gmail.com (grflanagan at gmail.com) Date: Wed, 27 Feb 2008 08:08:20 -0800 (PST) Subject: Getting python docstings References: <47BE97A7.5030509@behnel.de> <8ad1adcc-c299-418c-a214-88b5be9fd436@c33g2000hsd.googlegroups.com> <6287qgF21f45aU3@mid.uni-berlin.de> <5c37843d-aa8e-4aea-9233-4c8a22ccab20@e6g2000prf.googlegroups.com> <55a07cc0-6967-4b10-a162-195736fdc9d3@u69g2000hse.googlegroups.com> Message-ID: <2f9289d4-2645-4309-aad0-1394f407192f@c33g2000hsd.googlegroups.com> On Feb 27, 3:42 pm, Rufman wrote: > ok...i took a look at epydoc. I can produce html documentation, but > when i try to generate a pdf, I get this error: > > Error: latex failed: File `fancyhdr.sty' not found.latex: Error > response from server: 404 > > my system: > - MiKTeX2.7 installed > - windows xp > - ghostscript 8.60 > > Thanks for the help > > Stephane Don't know anything about EpyDoc (maybe try under cygwin?), but one way to get a pdf from a reST document is to use `rst2latex.py` which comes with docutils, then use MikTeX to generate a pdf from the LaTeX. Gerard From loquehumaine at gmail.com Fri Feb 8 06:07:53 2008 From: loquehumaine at gmail.com (LHB) Date: Fri, 08 Feb 2008 12:07:53 +0100 Subject: __builtins__ In-Reply-To: <612lj5F1tbd9kU1@mid.uni-berlin.de> References: <612lj5F1tbd9kU1@mid.uni-berlin.de> Message-ID: <47ac380f$0$23597$426a74cc@news.free.fr> Marc 'BlackJack' Rintsch a ?crit : > On Fri, 08 Feb 2008 00:25:14 -0800, loquehumaine wrote: > >> I have seen that if I type help() at a prompt, and then 'modules', >> I'll be given a list of all modules available, thanks to this group.. >> But I have seen the differences between them and the one in >> dir(__builtins__). >> Why are some modules in __builtins__ and others don't ? (UserDict for >> example) > > `__builtins__` doesn't contain modules:: You are right... I don't know why I thought there was math here... It's not in sys.modules either... Is there "a place" where you can find a list of 'some' available modules ('standard' ones like math, sys, ...) but not all, or I really need a break during the week-end? If so, what the difference between the 'present' and the 'missing' ones? For example, in http://docs.python.org/modindex.html for math: "This module is always available." unlike pickle or HTMLParser. Is this only because of the versions of Python? I think I have mixed-up a lot of things and that I need a little bit more of readings about builtin things... (Doc that goes further than http://docs.python.org/lib/builtin.html) > Python 2.4.4 (#2, Apr 12 2007, 21:03:11) > [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import inspect > >>> inspect.getmembers(__builtins__, inspect.ismodule) > [] At least I have learn a new module =) > `__builtins__` is an implementation detail, and `__builtin__` is a name > of a module you can import. You should not use `__builtins__` but import > `__builtin__` and inspect that instead of `__builtins__`. Ok. Should I only see `__builtins__` as an access to builtin functions/exception/... ? > Don't ``del __builtins__`` in the first place. :-) Fair enough ^_^ > So the real question is, why you see 'math' in `__builtins__`. It should > not be there. I think the answer is that I need more rest... > > Ciao, > Marc 'BlackJack' Rintsch Thanks a lot, LHB From JesseAldridge at gmail.com Mon Feb 25 02:40:25 2008 From: JesseAldridge at gmail.com (Jesse Aldridge) Date: Sun, 24 Feb 2008 23:40:25 -0800 (PST) Subject: Weird cgi error Message-ID: I uploaded the following script, called "test.py", to my webhost. It works find except when I input the string "python ". Note that's the word "python" followed by a space. If I submit that I get a 403 error. It seems to work fine with any other string. What's going on here? Here's the script in action: http://crookedgames.com/cgi-bin/test.py Here's the code: #!/usr/bin/python print "Content-Type: text/html\n" print """
""" From mwilson at the-wire.com Thu Feb 21 10:11:52 2008 From: mwilson at the-wire.com (Mel) Date: Thu, 21 Feb 2008 10:11:52 -0500 Subject: Globals or objects? References: Message-ID: James Newton wrote: > Duncan Booth wrote: >> The easiest way in Python to implement a singleton is just to >> use a module: all modules are singletons and there is a >> defined mechanism (import) for accessing them. [ ... ] > Could you give a bare-bones demonstration of it that the relative newbie > that I am can understand? I had a club-membership application that ran for several years. Default pathnames, etc. for the particular year came from a module called thisyear.py: #========================= '''Values used to access this years trakkers files. $Id: thisyear.py,v 1.2 2006/08/26 16:30:23 mwilson Exp $ ''' memberpath = '2006-7/20062007.txt' # path to this years membership CSV dirname = '2006-7' # directory name for this year #========================= Programs that needed to use the comma-separated-value membership base would import thisyear, and pass thisyear.memberpath when creating the CSV reader object. Etc. Mel. From larry.bates at websafe.com Wed Feb 20 09:15:06 2008 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 20 Feb 2008 08:15:06 -0600 Subject: is this data structure build-in or I'll have to write my own class? In-Reply-To: References: Message-ID: Jorge Vargas wrote: > I need a data structure that will let me do: > > - attribute access (or index) > - maintain the order (for iter and print) > - be mutable. > > in case there isn't one. I was thinking having a base class like Bunch > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308 and on > top of that keeping a list of the keys and pop/push to the list when > adding/deleting items. I don't like this idea because I'll have to > keep each key twice. (in the list and in __dict__, is this the only > way of doing it? Sounds like a good time to learn ElementTree (included in Python 2.5 but available for earlier versions). -Larry From tamim.shahriar at gmail.com Thu Feb 21 09:26:17 2008 From: tamim.shahriar at gmail.com (subeen) Date: Thu, 21 Feb 2008 06:26:17 -0800 (PST) Subject: newbie in python References: <1d24edf1-78f1-420e-9ca5-ef7e810e20cc@72g2000hsu.googlegroups.com> <9f540144-9ff5-4c95-8b7d-c65df3d9a9ee@h25g2000hsf.googlegroups.com> Message-ID: Dive into Python is a very good book but it's for people who have experience in other languages. I liked the book. Whatever book you read, please take a look at the Python Tutorial: http://docs.python.org/tut/tut.html, it will help. regards, Subeen. http://love-python.blogspot.com/ On Feb 21, 6:01 pm, 7stud wrote: > ctechnic... at gmail.com wrote: > > Hi anyone > > > I'm very interesed to learn python and really willing to do so,but > > unfortunately dont know where to start, or what programs need to > > install to start. > > > Can someone help me to get in the right track, and get a good move? > > > Thanks for all help > > If you're a good student or you have prior programming experience, get > the book 'Learning Python', which just came out with a 3rd edition, so > it is the most up to date book. > > If you are not such a good student or have no prior programming > experience, and you want a gentler introduction to python, check out > the book 'Python Programming for the Absolute Beginner(2nd Ed.)' From gagsl-py2 at yahoo.com.ar Fri Feb 15 20:17:49 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 15 Feb 2008 23:17:49 -0200 Subject: returning regex matches as lists References: <23eadf01-4c64-4abd-8f53-186c4387baff@s13g2000prd.googlegroups.com> Message-ID: En Fri, 15 Feb 2008 17:07:21 -0200, Jonathan Lukens escribi?: > I am in the last phase of building a Django app based on something I > wrote in Java a while back. Right now I am stuck on how to return the > matches of a regular expression as a list *at all*, and in particular > given that the regex has a number of groupings. The only method I've > seen that returns a list is .findall(string), but then I get back the > groups as tuples, which is sort of a problem. Do you want something like this? py> re.findall(r"([a-z]+)([0-9]+)", "foo bar3 w000 no abc123") [('bar', '3'), ('w', '000'), ('abc', '123')] py> re.findall(r"(([a-z]+)([0-9]+))", "foo bar3 w000 no abc123") [('bar3', 'bar', '3'), ('w000', 'w', '000'), ('abc123', 'abc', '123')] py> groups = re.findall(r"(([a-z]+)([0-9]+))", "foo bar3 w000 no abc123") py> groups [('bar3', 'bar', '3'), ('w000', 'w', '000'), ('abc123', 'abc', '123')] py> [group[0] for group in groups] ['bar3', 'w000', 'abc123'] -- Gabriel Genellina From stefan_ml at behnel.de Fri Feb 15 11:06:47 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 15 Feb 2008 17:06:47 +0100 Subject: Turtle graphics speed(). Seems broken In-Reply-To: References: Message-ID: <47B5B897.2030300@behnel.de> Alexander.Oot at gmail.com wrote: > I think the speed function may be broken from the turtle graphics > package > > > "from turtle import * > > speed('fastest') > > forward(50)" > > > I have tried all of the different speed settings, but I get no change > in the turtle's speed.... does anyone know how to fix this? Use "xturtle"? :) http://ada.rg16.asn-wien.ac.at/~python/xturtle/ Stefan From afriere at yahoo.co.uk Mon Feb 18 21:02:06 2008 From: afriere at yahoo.co.uk (Asun Friere) Date: Mon, 18 Feb 2008 18:02:06 -0800 (PST) Subject: Seemingly odd 'is' comparison. References: <47b36135$0$26076$88260bb3@free.teranews.com> <13rk2ho7b8h1c85@corp.supernews.com> <8cafcd9e-6a61-483f-b8f3-6e7b0e5ab435@s8g2000prg.googlegroups.com> Message-ID: <3af25e59-80d7-483e-a5ea-75e557f59edc@i29g2000prf.googlegroups.com> On Feb 19, 12:27 pm, Asun Friere wrote: > But given the nature of immutables I meant to write "given the nature of mutables" of course ... :/ From sjmachin at lexicon.net Tue Feb 26 15:29:59 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 26 Feb 2008 12:29:59 -0800 (PST) Subject: Regular Expression Help References: <17392f32-4bbc-4a03-b74e-38626d74e403@p73g2000hsd.googlegroups.com> Message-ID: On Feb 27, 6:28 am, Lytho... at gmail.com wrote: > Hi All, > > I have a python utility which helps to generate an excel file for > language translation. For any new language, we will generate the excel > file which will have the English text and column for interested > translation language. The translator will provide the language string > and again I will have python utility to read the excel file target > language string and update/generate the resource file & database > records. Our application is VC++ application, we use MS Access db. > > We have string table like this. > > "STRINGTABLE > BEGIN > IDS_CONTEXT_API_ "API Totalizer Control Dialog" > IDS_CONTEXT "Gas Analyzer" > END > > STRINGTABLE > BEGIN > ID_APITOTALIZER_CONTROL > "Start, stop, and reset API volume flow > \nTotalizer Control" > END > " > this repeats..... > > I read the file line by line and pick the contents inside the > STRINGTABLE. > > I want to use the regular expression while should give me all the > entries with in > STRINGTABLE > BEGIN > <> > END > > I tried little bit, but no luck. Note that it is multi-line string > entries which we cannot make as single line > Looks to me like you have a very simple grammar: entry ::= id quoted_string id is matched by r'[A-Z]+[A-Z_]+' quoted_string is matched by r'"[^"]*"' So a pattern which will pick out one entry would be something like r'([A-Z]+[A-Z_]+)\s+("[^"]*")' Not that using \s+ (whitespace) allows for having \n etc between id and quoted_string. You need to build a string containing all the lines between BEGIN and END, and then use re.findall. If you still can't get it to work, ask again -- but do show the code from your best attempt, and reduce ambiguity by showing your test input as a Python expression e.g. test1_in = """\ ID_F "fough" ID_B_ "barre" ID__Z "zotte start zotte end" """ From mwilson at the-wire.com Sun Feb 3 18:31:46 2008 From: mwilson at the-wire.com (Mel) Date: Sun, 03 Feb 2008 18:31:46 -0500 Subject: Is it explicitly specified? References: <60lqmqF1rkeiqU1@mid.individual.net> <60m2qnF1rgp7fU1@mid.uni-berlin.de> Message-ID: Steve Holden wrote: > Diez B. Roggisch wrote: >> Bjoern Schliessmann schrieb: >>> mario ruggier wrote: >>> >>>> It may sometimes be useful to make use of the conceptual >>>> difference between these two cases, that is that in one case the >>>> user did not specify any key and in the other the user explicitly >>>> specified the key to be None. >>> Do you have an example where this might be useful? >> >> Any situation in which there would otherwise lots of documentation >> needed to inform the user that the sentinel value is something else >> than None. >> >> Take something like this as an example: >> >> def update_user(some, values, nullable_value=sentinel): >> # first, work with some and values >> ... >> # then, on something actually being passed to nullable_value >> if nullable_value is not sentinel: >> connection.cursor().execute("update table set value = ?", >> nullable_value) >> >> >> >> I've seen this before, in code from e.g. Alex Martelli. >> > Sure, but the OP's question was "Is there any way to tell between > whether a keyword arg has been explicitly specified (to the same value > as the default for it)". We've drifted a long way from that, since the > code you demonstrate doesn't detect an explicit call with > nullable_value==sentinel -- the reason being, I submit, that there is no > use case for such code. The code above works on the assumption that the value named sentinel is completely out-of-band, and no user has any reason to use the sentinel object in a call. An example up-thread uses a uniquely-constructed instance of object for this. I kind of like defining a class, because I get a docstring to explain what's going on. Mel. From nick at stinemates.org Mon Feb 18 21:09:40 2008 From: nick at stinemates.org (Nick Stinemates) Date: Mon, 18 Feb 2008 18:09:40 -0800 Subject: Threading the Python interpreter In-Reply-To: References: Message-ID: <47BA3A64.4040005@stinemates.org> MooJoo wrote: > I've read that the Python interpreter is not thread-safe but are there > any issues in creating threads that create new processes (not threads) > that run new instantiations of python? What I'm doing is subclassing the > threading.Thread and, in the run method, I'm making a call to os.system, > passing to it another python script which then processes a file. When > the call to os.system completes, the thread is finished. Here is a > simplified fragment of code for what I'm doing. > > from threading import Thread > import os > > class MyThread(Thread): > def __init__(self, fn): > Thread.__init__(self) > self.fn = fn > > def run(self): > pyscript = '/usr/bin/env python script.py %s'%self.fn > status = os.system(pyscript) > > thr = MyThread('test.dat') > thr.start() > thr.join() > > Since I'm running each python instance in a new process, I don't believe > that there is a problem and, in my testing so far, I haven't encountered > anything that would lead me to believe there is a potential time bomb > here. Am I correct in my assumption this is OK or just lucky so far? > FYI -- That's not multi threading that's multiprocessing. You're safe. -- ================== Nick Stinemates (nick at stinemates.org) http://nick.stinemates.org AIM: Nick Stinemates MSN: nickstinemates at hotmail.com Yahoo: nickstinemates at yahoo.com ================== From duncan.booth at invalid.invalid Mon Feb 25 10:12:23 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 25 Feb 2008 15:12:23 GMT Subject: Using lambda [was Re: Article of interest: Python pros/cons for theenterprise] References: <036e93e6-5840-4a3c-8642-67a0a9ec44f2@i7g2000prf.googlegroups.com> <784ec210-f389-4a15-b458-961100de9103@v3g2000hsc.googlegroups.com> <5MSdncqVGdEXiSPanZ2dnUVZ_vPinZ2d@comcast.com> <7xwsoxd00c.fsf@ruckus.brouhaha.com> <7xmyprtay1.fsf@ruckus.brouhaha.com> <88qdnQR0a7V7Rl3anZ2dnUVZ_rqlnZ2d@comcast.com> <7xmyprf3ef.fsf@ruckus.brouhaha.com> <13s5kclk4maa584@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > On Sun, 24 Feb 2008 21:13:08 -0500, Terry Reedy wrote: > >> | I even use "named anonymous functions" *cough* by assigning lambda | >> functions to names: >> | >> | foo = lambda x: x+1 >> >> Even though I consider the above to be clearly inferior to >> >> def foo(x): return x+1 >> >> since the latter names the function 'foo' instead of the generic >> ''. > > Absolutely. If foo() was a function that the user would see, I would > certainly use the def form to create it. > > But in a situation like this: > > > def parrot(x, y, z, func=None): > if func is None: > func = lambda x: x+1 > return func(x+y+z) > > > I don't see any advantage to writing it as: > > def parrot(x, y, z, func=None): > if func is None: > def func(x): return x+1 > return func(x+y+z) > > > I take it you never feel the need to inspect tracebacks, nor insert a breakpoint or print statement at an arbitrary point in the code. Granted none of those may apply in this particular simple case, but if you pass functions/lambdas around a lot it can be frustrating when you get an error such as: TypeError: () takes exactly 2 arguments (1 given) and the traceback only tells you which line generated the TypeError, not which lambda was involved. On the other hand: TypeError: parrot_func() takes exactly 2 arguments (1 given) while it might not identify the function uniquely in all situations at least tells you something useful about the function being called. From wdh2442 at gmail.com Sun Feb 3 11:08:41 2008 From: wdh2442 at gmail.com (kaki) Date: Sun, 3 Feb 2008 08:08:41 -0800 (PST) Subject: interested???? Message-ID: <95237c1a-49f2-49fd-9869-81f662e8cb3e@l32g2000hse.googlegroups.com> click here: http://kg-azfari.myminicity.com/ From castironpi at gmail.com Wed Feb 13 21:05:47 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 13 Feb 2008 18:05:47 -0800 (PST) Subject: Regular Expression for Prime Numbers (or How I came to fail at them, and love the bomb) References: <85ca4615-c51f-4aab-b400-f3f80056faec@l32g2000hse.googlegroups.com> Message-ID: <58cc72e3-2b83-47c9-b052-1ca8ffe083a5@s19g2000prg.googlegroups.com> On Feb 13, 5:43?pm, Mark Dickinson wrote: > On Feb 13, 5:14?pm, castiro... at gmail.com wrote: > > > Isn't the finite state machine "regular expression 'object'" really > > large? > > There's no finite state machine involved here, since this isn't a > regular expression in the strictest sense of the term---it doesn't > translate to a finite state machine, since backreferences are > involved. > > Mark What is it? From jakub.hrozek at gmail.com Mon Feb 4 07:29:40 2008 From: jakub.hrozek at gmail.com (jakub.hrozek at gmail.com) Date: Mon, 4 Feb 2008 04:29:40 -0800 (PST) Subject: polling for output from a subprocess module Message-ID: <48dec8a9-c2da-492c-a639-097fe25fe73c@s8g2000prg.googlegroups.com> Hello, My program uses the subprocess module to spawn a child and capture its output. What I'd like to achieve is that stdout is parsed after the subprocess finishes, but anything that goes to stderr is printed immediately. The code currently looks like: try: test = Popen(test_path, stdout=PIPE, stderr=PIPE, close_fds=True, env=test_environ) while test.poll() == None: ready = select.select([test.stderr], [], []) if test.stderr in ready[0]: t_stderr_new = test.stderr.readlines() if t_stderr_new != []: print "STDERR:", "\n".join(t_stderr_new) t_stderr.extend(t_stderr_new) except OSError, e: print >>sys.stderr, _("Test execution failed"), e else: self.result.return_code = test.returncode self.result.process(test.stdout.readlines(), t_stderr) The problem is, that it seems that all the output from the subprocess seems to be coming at once. Do I need to take a different approach? From bbxx789_05ss at yahoo.com Fri Feb 22 16:31:39 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Fri, 22 Feb 2008 13:31:39 -0800 (PST) Subject: n00b with urllib2: How to make it handle cookie automatically? References: Message-ID: <77056cd3-7445-4beb-b45a-db4141e0c0a1@s13g2000prd.googlegroups.com> On Feb 21, 11:50?pm, est wrote: > Hi all, > > I need urllib2 do perform series of HTTP requests with cookie from > PREVIOUS request(like our browsers usually do ). Many people suggest I > use some library(e.g. pycURL) instead but I guess it's good practise > for a python beginner to DIY something rather than use existing tools. > > So my problem is how to expand the urllib2 class > > from cookielib import CookieJar > class SmartRequest(): > ? ? cj=CookieJar() > ? ? def __init__(self, strUrl, strContent=None): > ? ? ? ? self.Request ? ?= ? urllib2.Request(strUrl, strContent) > ? ? ? ? self.cj.add_cookie_header(self.Request) > ? ? ? ? self.Response ? = ? urllib2.urlopen(Request) > ? ? ? ? self.cj.extract_cookies(self.Response, self.Request) > ? ? def url > ? ? def read(self, intCount): > ? ? ? ? return self.Response.read(intCount) > ? ? def headers(self, strHeaderName): > ? ? ? ? return self.Response.headers[strHeaderName] > > The code does not work because each time SmartRequest is initiated, > object 'cj' is cleared. That's because every time you create a SmartRequest, this line executes: cj=CookieJar() That creates a new, *empty* cookie jar, i.e. it has no knowledge of any previously set cookies. > How to avoid that? If you read the docs on the cookielib module, and in particular CookieJar objects, you will notice that CookieJar objects are described in a section that is titled: CookieJar and FileCookieJar Objects. Hmm...I wonder what the difference is between a CookieJar object and a FileCookieJar Object? ---------- FileCookieJar implements the following additional methods: save(filename=None, ignore_discard=False, ignore_expires=False) Save cookies to a file. load(filename=None, ignore_discard=False, ignore_expires=False) Load cookies from a file. -------- That seems promising. From steve at holdenweb.com Sat Feb 9 23:05:34 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 09 Feb 2008 23:05:34 -0500 Subject: Error on Python In-Reply-To: References: <2713302a-dade-4c5d-9eba-eb73f4f03d6f@s12g2000prg.googlegroups.com> Message-ID: <47AE780E.60008@holdenweb.com> Tim Roberts wrote: > maehhheeyy wrote: > >> Hi, right now I'm using Python and Multicast. I have the code for >> Multicast receiver on Python but I keep getting this error; >> >> File "", line 1, in bind >> error: (10049, "Can't assign requested address") >> >> The error is coming from this line; >> sock.bind ((MCAST_ADDR, MCAST_PORT)) >> >> Can anyone please help me solve this problem? > > Where did you get the multicast module? Are you trying to do TCP > multicast? What is the address you are trying to use? TCP multicast? That doesn't make sense, there can only be two endpoints to a TCP connection. But *you* know that. Couldn't the port just be in use? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Feb 22 03:03:44 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 22 Feb 2008 09:03:44 +0100 Subject: Article of interest: Python pros/cons for the enterprise In-Reply-To: References: <2f1527a7-2f66-44c7-9665-4d8ff01fa5ab@28g2000hsw.googlegroups.com> <47bd4a24$0$25225$426a74cc@news.free.fr> Message-ID: <47be8175$0$7872$426a74cc@news.free.fr> Nicola Musatti a ?crit : > On Feb 21, 10:55 am, Bruno Desthuilliers 42.desthuilli... at wtf.websiteburo.oops.com> wrote: >> Carl Banks a ?crit : > [...] >>> C++ is a compile-time, type-checked language, which means it is >>> totally safer for newbies than Python. Yep, your big company is >>> totally safe with newbie C++ programmers. >> Mouarf ! Brillant demonstration, thanks Carl !-) >> >> (and BTW, +1 QOTW) > > Newbies learn, and the fundamental C++ lessons are usually learnt > quite easily. Which is why the most common source of nasty bugs in C++ apps - even coded by experimented, careful and talented programmers -has to do with dangling pointers, memory leaks, erroneous typecasts and other related niceties... Things that are somewhat less likely to happen in Python. > Unless we're talking about idiots, that is, but in this > case at least C++ is likely to make their deficiencies evident sooner > than most other programming languages. Here at least you have a point !-) > So, yes, your big company is > likely to be safer with newbie C++ programmers than with Python newbie > programmers. Sorry but I don't buy your arguments. > Had we been speaking of productivity... but we weren't, were we? Should we ?-) From bharathv6 at gmail.com Tue Feb 26 01:36:06 2008 From: bharathv6 at gmail.com (bharath venkatesh) Date: Tue, 26 Feb 2008 12:06:06 +0530 Subject: running a daemon in python Message-ID: <910313af0802252236x36e50d4di4f39d9e45d26d6fc@mail.gmail.com> hi .. hi i want a program to start running as daemon in background .. my program is server listen to a client ... so i want to make that program run as daemon .. when i execute the program the program for ex server.py it should automatically start running as daemon in the background even if i close the terminal it shouldn't stop executing.. (right now if i close the terminal the process exits) can any one tell how to do it in python as i have implemented the server in python ... -------------- next part -------------- An HTML attachment was scrubbed... URL: From robinsiebler at gmail.com Wed Feb 13 18:01:28 2008 From: robinsiebler at gmail.com (robinsiebler at gmail.com) Date: Wed, 13 Feb 2008 15:01:28 -0800 (PST) Subject: Floating point bug? Message-ID: I've never had any call to use floating point numbers and now that I want to, I can't! *** Python 2.5.1 (r251:54863, May 1 2007, 17:47:05) [MSC v.1310 32 bit (Intel)] on win32. *** >>> float (.3) 0.29999999999999999 >>> foo = 0.3 >>> foo 0.29999999999999999 >>> From mc0710 at gmail.com Wed Feb 13 04:55:20 2008 From: mc0710 at gmail.com (mc0710 at gmail.com) Date: Wed, 13 Feb 2008 01:55:20 -0800 (PST) Subject: Python not finding modules Message-ID: Hey! I installed a few python modules through the freebsd ports, but when I try to import them in the interpreter it says "module xxx not found". This seems to happen for some modules and not for the others. ex:- I installed psyco and parallel python which seem to be found but then scipy, PIL aren't being imported. Below is my $PYTHONPATH ['', '/usr/local/lib/python2.5/site-packages/setuptools-0.6c7- py2.5.egg', '/usr/local/lib/python25.zip', '/usr/local/lib/python2.5', '/usr/local/lib/python2.5/plat-freebsd6', '/usr/local/lib/python2.5/ lib-tk', '/usr/local/lib/python2.5/lib-dynload', '/usr/local/lib/ python2.5/site-packages', '/usr/local/lib/python2.5/site-packages/ gtk-2.0', '/usr/local/lib/vtk/python', '/usr/local/lib/python2.5/site- packages'] The scipy libs are located at "/usr/local/lib/python2.4/site-packages/ scipy" so I manually added this path to the PYTHONPATH but it still doesn't seem to find it. Can someone please help me out here?:) ps Also does including a directory in PYTHONPATH include all of it's sub-directories too? From ptmcg at austin.rr.com Fri Feb 1 12:20:50 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 1 Feb 2008 09:20:50 -0800 (PST) Subject: How to convert markup text to plain text in python? References: <47A34870.3090700@tim.thechases.com> Message-ID: <50cdeff0-a284-4266-add3-97ff13132482@q77g2000hsh.googlegroups.com> On Feb 1, 10:54?am, Tim Chase wrote: > >> Well, if all you want to do is remove everything from a "<" to a > >> ">", you can use > > >> ? >>> s = "Today is Friday" > >> ? >>> import re > >> ? >>> r = re.compile('<[^>]*>') > >> ? >>> print r.sub('', s) > >> ? Today is Friday > > [Tim's ramblings about pathological cases snipped] pyparsing includes an example script for stripping tags from HTML source. See it on the wiki at http://pyparsing.wikispaces.com/space/showimage/htmlStripper.py. -- Paul From lists at cheimes.de Wed Feb 20 08:51:32 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 20 Feb 2008 14:51:32 +0100 Subject: threaded http server In-Reply-To: <910313af0802200417if1e6422p47ca1a22cb23c8ac@mail.gmail.com> References: <910313af0802200417if1e6422p47ca1a22cb23c8ac@mail.gmail.com> Message-ID: bharath venkatesh wrote: > hi > i want to create fast n efficient http server which serve multiple > client concurrently .. so i thought of threading the http server using Threads ain't efficient for IO bound problems like a HTTP server. Most OSs have far better ways to deal with IO bound applications like select(), poll(), epoll(), kqueue() or IOCP. Use Twisted :) Christian From jorge.vargas at gmail.com Wed Feb 27 05:45:44 2008 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Wed, 27 Feb 2008 04:45:44 -0600 Subject: library In-Reply-To: <420352.33502.qm@web8712.mail.in.yahoo.com> References: <420352.33502.qm@web8712.mail.in.yahoo.com> Message-ID: <32822fe60802270245g13e32f89ne07c1743285e24d4@mail.gmail.com> On Tue, Feb 26, 2008 at 11:24 PM, Raj kumar wrote: > > hi, > how to open python api documetation in linux machine? $ python import help(module|object|whatever) > i think there should be a way to open installed library as a HTML pages. > pydoc -p > Thanks in advance. > > > ________________________________ > Save all your chat conversations. Find them online. > -- > http://mail.python.org/mailman/listinfo/python-list > From martin at v.loewis.de Tue Feb 12 16:02:14 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 12 Feb 2008 22:02:14 +0100 Subject: Unicode char replace In-Reply-To: <43028c04-d9bb-4708-b08e-8c6fd2c113ba@1g2000hsl.googlegroups.com> References: <43028c04-d9bb-4708-b08e-8c6fd2c113ba@1g2000hsl.googlegroups.com> Message-ID: <47b20956$0$2660$9b622d9e@news.freenet.de> > string = u'Macworld ? Jobs 1 - Twitter 0' > > > None of them gives me 'Macworld » Jobs 1 - Twitter 0' > > Any idea? So I assume you *want* it to produce ». May I ask why? I really recommend that you use » instead. In any case, you need to define your own error handler, such as the one in http://herlock.com/ob/pythoncb/0596007973/chp-1-sect-23.html HTH, Martin From ph at spirali.ru Fri Feb 1 11:34:25 2008 From: ph at spirali.ru (ph) Date: Fri, 1 Feb 2008 19:34:25 +0300 Subject: How to convert markup text to plain text in python? In-Reply-To: References: Message-ID: <20080201163425.GB400@ph-laptop> On 01-Feb-2008, geoffbache wrote: > I have some marked up text and would like to convert it to plain text, > by simply removing all the tags. Of course I can do it from first > principles but I felt that among all Python's markup tools there must > be something that would do this simply, without having to create an > XML parser etc. > > I've looked around a bit but failed to find anything, any tips? > > (e.g. convert "Today is Friday" to "Today is Friday") Quick but very dirty way: data=urllib.urlopen('http://google.com').read() data=''.join([x.split('>',1)[-1] for x in data.split('<')]) From jeff at schwabcenter.com Sat Feb 16 00:08:43 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Fri, 15 Feb 2008 21:08:43 -0800 Subject: Passing a callable object to Thread In-Reply-To: References: <52465ed8-7d25-40ca-be69-478b308af879@u10g2000prn.googlegroups.com> <7xir0psq9l.fsf@ruckus.brouhaha.com> <452d63ea-3373-4393-9c28-38116f96d2e9@u10g2000prn.googlegroups.com> <7xzlu1bmdj.fsf@ruckus.brouhaha.com> Message-ID: Steve Holden wrote: > Paul Rubin wrote: >> Steve Holden writes: >>> Assuming you're right, what alternative would you suggest? Would it >>> allow parenthesized expressions to retain their customary meaning? >> >> It is kind of weird that there is even such a thing as a 1-tuple. > > I agree that zero-length and singleton tuples don't make a great deal of > sense semantically. Why not? They seem intuitive to me. I would find it weird if you couldn't have 0-tuple, and even weirder if you couldn't have a 1-tuple. Maybe my brain has been warped by too much C++ code. In C++, it's very common to define data structures that have no members; the moral equivalent of an empty tuple: struct S { }; I recently did this in C, and was surprised to see this message from gcc: main.c:1: warning: struct has no members It's also common in C++ to treat a stand-alone object as an array of length 1. This is useful because any function defined to take a sequence of input can easily be given a single element instead: int proto = 5; std::vector v(&proto, &proto + 1); It strikes me that 1-tuples could serve the same purpose. It's common now for functions to be defined to take single elements, with client code using loops to process sequences: for item in sequence: process(item) If functions were instead defined to take sequences, then client code would be simplified, especially for common tasks like processing lines of input. process(sequence) On occasions when only a single item were to be processed, a 1-tuple would serve as a nice syntactic adapter: process((item,)) From danb_83 at yahoo.com Sat Feb 16 19:21:56 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Sat, 16 Feb 2008 16:21:56 -0800 (PST) Subject: Floating point bug? References: <6eba298e-6888-462a-afa7-54fae02c3dce@y5g2000hsf.googlegroups.com> <61ibo1F1uqso2U1@mid.uni-berlin.de> <188be6e9-bc05-4a72-924b-1de184980002@n58g2000hsf.googlegroups.com> Message-ID: <275db15d-e2a8-417d-9c39-fcf813c34b5a@i29g2000prf.googlegroups.com> On Feb 14, 8:10 pm, Zentrader wrote: > > That's a misconception. The decimal-module has a different base (10 > > instead of 2), and higher precision. But that doesn't change the fact > > that it will expose the same rounding-errors as floats do - just for > > different numbers. > > > >>> import decimal as d > > >>> d = d.Decimal > > >>> d("1") / d("3") * d("3") > > Decimal("0.9999999999999999999999999999") > > Surely you jest. He's not joking at all. > Your example is exact to 28 digits. Your attempted > trick is to use a number that never ends (1/3=0.3333...). It does end in base 3, 6, 9, 12, etc. You have to remember that base-ten wasn't chosen because it has mathematical advantages over other bases, but merely because people counted on their fingers. In light of this fact, why is one-fifth more deserving of an exact representation than one-third is? From tenax.raccoon at gmail.com Mon Feb 4 10:25:57 2008 From: tenax.raccoon at gmail.com (Jason) Date: Mon, 4 Feb 2008 07:25:57 -0800 (PST) Subject: type, object hierarchy? References: <814a05b4-6f13-4c86-8c68-a30da06ca093@b2g2000hsg.googlegroups.com> <2ba95819-0699-49c6-b7e9-96d54763be52@v17g2000hsa.googlegroups.com> <4a2fabf4-5a4d-4afc-a722-f2887da10d1f@q39g2000hsf.googlegroups.com> Message-ID: <8d206c5f-8dbd-4951-87a2-bedd5d5c834d@e4g2000hsg.googlegroups.com> On Feb 3, 10:31 pm, 7stud wrote: > On Feb 3, 10:28 pm, 7stud wrote: > > > From the docs: > > > issubclass(class, classinfo) > > Return true if class is a subclass (direct or indirect) of classinfo. > > print issubclass(Dog, object) #True > print issubclass(type, object) #True > print issubclass(Dog, type) #False Yes. That is exactly what is expected. Dog is not subclassed from type. It is subclassed from Mammals, which is subclassed from object. Dog is, however, an instance of type. This is true of all new-style Python classes. All of Python's classes are objects. They have to be an instance of / something/. New-style classes are instances of the class type. That doesn't mean that they are considered subclasses from class type. This means that the Dog object has all the methods, properties, and class data that the class type has. Class type is Dog's metaclass -- the class of the class. If you create an instance of Dog, you can access the various class attributes that Dog has through the instance. It doesn't mean that the instance of Dog is subclassed from Dog. >>> terrier = Dog() >>> issubclass(terrier, Dog) Traceback (most recent call last): File "", line 1, in TypeError: issubclass() arg 1 must be a class In Python, you can create a subclass of class type. This isn't very useful in most cases. If you set the __metaclass__ magick attribute, however, your class object will be an instance of the class referred to by that attribute. This lets you experiment with the way classes are created and how the MRO works, and lets you break Python at a pretty low level. For example: >>> class NewTalky(type): ... def __new__(*args, **keyargs): ... print "I am called when Python creates a class whose metaclass is me." ... print "I am responsible for creating a class object." ... print "My ordered arguments:", args ... print "My keyword arguments:", keyargs ... classObject = type.__new__(*args, **keyargs) ... print "The result of type.__new__():", classObject ... return classObject ... >>> class Reptile(object): ... __metaclass__ = NewTalky ... I am called when Python creates a class whose metaclass is me. I am responsible for creating a class object. My ordered arguments: (, 'Reptile', (,), {'__module__': '__main__', '__metaclass__': }) My keyword arguments: {} The result of type.__new__(): >>> >>> type(Dog) # Dog is an instance of class type >>> type(Reptile) # Reptile is an instance of class NewTalky >>> >>> issubclass(Reptile, type) # Reptile is not subclassed from type... False >>> issubclass( type(Reptile), type ) # ...but NewTalky is True >>> issubclass( type(Dog), type ) True >>> Again, everything in Python is an object. Your Python classes are class objects. They are instances of the class type. In the first example above, terrier is an instance of class Dog, but is not a subclass of class Dog. Similarly, Dog is an instance of class type, not a subclass of class type. Since class Dog is an instance of class type, class type is considered to be Dog's metaclass. You can create your own metaclasses. To quote another Pythoneer, if you think you need a metaclass, you probably don't. If you know you need a metaclass, you definitely do not need a metaclass. They are tricky and mind-bending. Hope this helps clear things up for you. --Jason From darcy at druid.net Tue Feb 26 10:17:08 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 26 Feb 2008 10:17:08 -0500 Subject: How about adding rational fraction to Python? In-Reply-To: References: <649ac8a9-ae09-4e9b-85c2-f37043af21fd@28g2000hsw.googlegroups.com> <0d1955fc-762c-44e1-a5d8-372c71458455@p25g2000hsf.googlegroups.com> <36204e6f-0d82-449b-8ca5-c819ace9a55a@p73g2000hsd.googlegroups.com> <9503b14b-7bd5-42b4-b3f7-673d0ebd7feb@c33g2000hsd.googlegroups.com> <602ac27c-4aaa-49b2-bee2-1e0e0c705983@i7g2000prf.googlegroups.com> <24caed07-c938-431b-b502-c75a9b6d3d70@t66g2000hsf.googlegroups.com> Message-ID: <20080226101708.ae82b86a.darcy@druid.net> On Tue, 26 Feb 2008 06:59:44 -0800 (PST) Lie wrote: > The problem lies on which maths is the real maths? In real world, 3/4 > is 0.75 is 0.75 and that's an unchangeable fact, so programming Which real world is that? In my real world 3/4 is 0 with a remainder of 3. What happens to that 3 depends on the context. When I worked with a youth soccer group I was pretty sure that I would be disciplined if I carved up a seven year old player so that I could put 0.75 of a child on a team. Anyway, I'm sure that all these arguments have been made and it is pointless to argue about it now. It sounds like the decision has been made. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From http Tue Feb 26 12:05:50 2008 From: http (Paul Rubin) Date: 26 Feb 2008 09:05:50 -0800 Subject: Article of interest: Python pros/cons for the enterprise References: <784ec210-f389-4a15-b458-961100de9103@v3g2000hsc.googlegroups.com> <5MSdncqVGdEXiSPanZ2dnUVZ_vPinZ2d@comcast.com> <7xwsoxd00c.fsf@ruckus.brouhaha.com> <7xr6f3f3ma.fsf@ruckus.brouhaha.com> <7xhcfzdlqc.fsf@ruckus.brouhaha.com> Message-ID: <7xmypnbqc1.fsf@ruckus.brouhaha.com> Nicola Musatti writes: > > http://search.barnesandnoble.com/booksearch/isbnInquiry.asp?EAN=97802... > Read the title. This is about "C Traps and Pitfalls". Whoops, I think the same author wrote a similar one about C++. He hangs out here on this newsgroup sometimes. I didn't notice that my keyword search got the wrong one. From steve at holdenweb.com Sat Feb 16 21:08:14 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 16 Feb 2008 21:08:14 -0500 Subject: Solve a Debate In-Reply-To: <823af984-c206-4d83-a2ab-f400eb907a14@e23g2000prf.googlegroups.com> References: <921723f8-bfc6-4339-85b7-dae17bc2f894@i29g2000prf.googlegroups.com> <823af984-c206-4d83-a2ab-f400eb907a14@e23g2000prf.googlegroups.com> Message-ID: John Machin wrote: > On Feb 17, 11:11 am, "Gabriel Genellina" > wrote: >> En Sat, 16 Feb 2008 19:43:37 -0200, John Machin >> escribi?: >> >>> On Feb 16, 3:48 pm, Dan Bishop wrote: >>>> days_in_month = lambda m: m - 2 and 30 + bool(1 << m & 5546) or 28 >>> Alternatively: >>> days_in_month = lambda m: m - 2 and 31 - ((m + 9) % 12 % 5 % 2) or 28 >>> the guts of which is slightly more elegant than the ancient writing >>> from which it was derived: >>> MOD(MOD(MOD(M+9,12),5),2) >> I wonder why one would write such arcane expressions [in Python] instead >> of using a small dictionary {1:31, 2:28, 3:31...} which is auto >> documented, obviously correct, several times faster, and provides input >> validation for free (days_in_month(13)?) >> > > Some people write such arcane expressions in Python solely for > amusement in the newsgroup. I suggest that if you actually find any > who write such expressions in Python *instead* of using a dictionary, > you should don your nice red uniform and arraign them before the > Inquisition forthwith. Not the comfy chair! -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From bbxx789_05ss at yahoo.com Mon Feb 25 06:08:09 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 25 Feb 2008 03:08:09 -0800 (PST) Subject: network programming: how does s.accept() work? References: <6d564fca-3884-4665-8a86-f7e658217a33@e60g2000hsh.googlegroups.com> <446482ef-1fd8-41dc-a8fd-44de8b51a8e8@o10g2000hsf.googlegroups.com> Message-ID: <379fcee4-15e0-48c2-863b-4b7458893cbe@h25g2000hsf.googlegroups.com> On Feb 25, 2:43?am, bock... at virgilio.it wrote: > On 25 Feb, 09:51, 7stud wrote: > > > > > I have the following two identical clients > > > #test1.py:----------- > > import socket > > > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > > host = 'localhost' > > port = 5052 ?#server port > > > s.connect((host, port)) > > print s.getsockname() > > > response = [] > > while 1: > > ? ? piece = s.recv(1024) > > ? ? if piece == '': > > ? ? ? ? break > > > ? ? response.append(piece) > > > #test3.py:---------------- > > import socket > > > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > > host = 'localhost' > > port = 5052 ?#server port > > > s.connect((host, port)) > > print s.getsockname() > > > response = [] > > while 1: > > ? ? piece = s.recv(1024) > > ? ? if piece == '': > > ? ? ? ? break > > > ? ? response.append(piece) > > > and this basic server: > > > #test2.py:-------------- > > import socket > > > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > > host = '' > > port = 5052 > > > s.bind((host, port)) > > s.listen(5) > > > while 1: > > ? ? newsock, client_addr = s.accept() > > ? ? print "orignal socket:", s.getsockname() > > > ? ? print "new socket:", newsock.getsockname() > > ? ? print "new socket:", newsock.getpeername() > > ? ? print > > > I started the server, and then I started the clients one by one. ?I > > expected both clients to hang since they don't get notified that the > > server is done sending data, and I expected the server output to show > > that accept() created two new sockets. ?But this is the output I got > > from the server: > > > original socket: ('0.0.0.0', 5052) > > new socket, self: ('127.0.0.1', 5052) > > new socket, peer: ('127.0.0.1', 50816) > > > original socket: ('0.0.0.0', 5052) > > new socket, self: ('127.0.0.1', 5052) > > new socket, peer: ('127.0.0.1', 50818) > > > The first client I started generated this output: > > > ('127.0.0.1', 50816) > > > And when I ran the second client, the first client disconnected, and > > the second client produced this output: > > > ('127.0.0.1', 50818) > > > and then the second client hung. ?I expected the server output to be > > something like this: > > > original socket: ('127.0.0.1', 5052) > > new socket, self: ('127.0.0.1', 5053) > > new socket, peer: ('127.0.0.1', 50816) > > > original socket: ('0.0.0.0', 5052) > > new socket, self: ('127.0.0.1', 5054) > > new socket, peer: ('127.0.0.1', 50818) > > > And I expected both clients to hang. ?Can someone explain how accept() > > works? > > I guess (but I did not try it) that the problem is not accept(), that > should work as you expect, > but the fact that at the second connection your code actually throws > away the first connection > by reusing the same variables without storing the previous values. > This could make the Python > garbage collector to attempt freeing the socket object created with > the first connection, therefore > closing the connection. > > If I'm right, your program should work as you expect if you for > instance collect in a list the sockets > returned by accept. > > Ciao > ---- > FB The question I'm really trying to answer is: if a client connects to a host at a specific port, but the server changes the port when it creates a new socket with accept(), how does data sent by the client arrive at the correct port? Won't the client be sending data to the original port e.g. port 5052 in the client code above? From planders at gmail.com Tue Feb 19 20:48:48 2008 From: planders at gmail.com (Preston Landers) Date: Tue, 19 Feb 2008 17:48:48 -0800 (PST) Subject: how to finish a while loop... References: <4b89dd2b-782c-4d07-ac6f-d5ae4b3b1b4c@s12g2000prg.googlegroups.com> <055ec51d-2119-45fd-9284-e70d88449a1a@j28g2000hsj.googlegroups.com> <772d5e87-0e0e-485b-b35f-0f9e09a3076f@i12g2000prf.googlegroups.com> Message-ID: <1446036c-d31e-4921-9b7d-5c9ac6e28530@h25g2000hsf.googlegroups.com> On Feb 19, 7:35 pm, icarus wrote: > > But when I paste it into eclipse and run it > > eclipse's console, it doesn't work because answer seems to have a > > stray '\r' carriage return (CR) and therefore the comparison to 'no' > > fails. > > I get no 'compile' errors there. > I get regular execution but it just doesn't change the > condition to False at the very end. > Therefore it loops forever. I used other values like zeros > and ones to make sure I could print the values when the interpreter > got down to that line. Everything checked. Just didn't change the > condition on the main loop. I'm pretty sure this is an eclipse console issue. Since you have it, try stepping through the program in the debugger and inspect the answer variable after raw_input returns. On my setup, at that point answer is 'no\r', but raw_input() is supposed to strip line endings. I'm guessing the console supplied 'no\r\n' and only the \n was stripped. Could be that python does not recognize that eclipse's console uses CRLF line endings. As a workaround you can do raw_input().strip(). You might check the eclipse issue tracker to see if this a known issue. Preston From castironpi at gmail.com Mon Feb 18 22:14:10 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 18 Feb 2008 19:14:10 -0800 (PST) Subject: The big shots Message-ID: <89d15587-e8de-444c-b240-4a10305146e0@e23g2000prf.googlegroups.com> I'm a little dissatisfied, and just thinking aloud. Some of the ideas that have been proposed on Python-ideas as well as Python, have received partial evaluation from the alphas. Lesser individuals than they could not have invented Python, and would be liable to ban me merely for this post. Notwithstanding. The reason they have cited is, "It is not in prevalent use." The printing press, rail, automobiles, and Python, were not in prevalent use before their invention. I.e., they -can't- come if one doesn't build it. However, there were writing, transportation, and programming before these respectively; does it merely suffice to answer, "Yes it is?" The Python gurus' combined professional judgement results in Python. Looking through http://www.python.org/dev/peps/ , their own proposals don't meet their own criteria. Start there. It is neither necessary nor sufficient that an expansion is or would be used. From steve at holdenweb.com Fri Feb 29 09:37:38 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 29 Feb 2008 09:37:38 -0500 Subject: pySQLite Insert speed In-Reply-To: <701b9c10-3753-43a4-ae98-63534616a36e@i29g2000prf.googlegroups.com> References: <701b9c10-3753-43a4-ae98-63534616a36e@i29g2000prf.googlegroups.com> Message-ID: mdboldin at gmail.com wrote: >> (B) is better than (A). The parameter binding employed in (B) >> is not only faster on many databases, but more secure. > See, for example,http://informixdb.blogspot.com/2007/07/filling-in- > blanks.html > > Thx. The link was helpful, and I think I have read similar things > before-- that B is faster. > So ... I just rewrote the test code from scratch and B is faster. I > must have had something wrong in my original timing. Don't forget, by the way, that your original (B) code was performing the string substitution of the parameter markers into the SQL statement each time the statement was executed. As Carsten pointed out, this overhead should be performed at most once, and only then if you want your code to be portable over database backends with different paramstyles. Forget (A). regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From Lie.1296 at gmail.com Sat Feb 16 17:10:28 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 16 Feb 2008 14:10:28 -0800 (PST) Subject: How about adding rational fraction to Python? References: <6eba298e-6888-462a-afa7-54fae02c3dce@y5g2000hsf.googlegroups.com> <61ibo1F1uqso2U1@mid.uni-berlin.de> <188be6e9-bc05-4a72-924b-1de184980002@n58g2000hsf.googlegroups.com> <9b166b3d-89df-4f26-956a-abbd391167e7@i12g2000prf.googlegroups.com> <13rcd3nskgpv91d@corp.supernews.com> <13rde22ktgpu532@corp.supernews.com> <26641b5f-d6cb-45a6-8736-7d130d1a5aee@u10g2000prn.googlegroups.com> <13a4316e-3ce7-4b3e-b418-6efb988a8845@q78g2000hsh.googlegroups.com> <676ca28c-b471-41c8-8661-fcd2ea8c23f0@i12g2000prf.googlegroups.com> <74b95b3b-1d6a-42a6-b55d-e77a868b1ffe@64g2000hsw.googlegroups.com> Message-ID: <1d1ecaa0-64ac-4ff3-9e05-4f3c6b2ca572@s12g2000prg.googlegroups.com> On Feb 17, 4:25?am, Carl Banks wrote: > On Feb 16, 3:03 pm, Lie wrote: > > > Although rationals have its limitations too, it is a much > > better choice compared to floats/Decimals for most cases. > > Maybe that's true for your use cases, but it's not true for most cases > in general. OK, that might have been an overstatement, but as I see it, it is safer to handle something in a Fraction compared to floats (which is why I uses fractions whenever possible in non-computer maths). > Rationals are pretty useless for almost any extended calculations, > since the denominator tends to grow in size till it's practically > unusbale, which means you have to periodically do non-exact reductions > to keep things running, and if you do that you might as well be using > floating point. Rationals aren't that good if the same piece of variable is to be calculated again and again because of its growth, but there are a lot of cases where the data would only require five or six or so operations done on it (and there are thousands or millions of such datas), rationals is the perfect choice for those situations because it is easier to use thanks to the comparison safety. Or in the situations where speed isn't as important and accuracy is required, Fraction may be faster than decimal and more accurate at the same time (someone need to test that though). > Rationals have their occasional special purpose uses, but for most > cases they're at best marginally better then floats and more often > incomparably worse. From dblubaugh at belcan.com Mon Feb 18 14:48:57 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Mon, 18 Feb 2008 14:48:57 -0500 Subject: Question In-Reply-To: <86380fd30802181016i4f1a0a22s9edf8cf353117b46@mail.gmail.com> References: <27CC3060AF71DA40A5DC85F7D5B70F38010E37C6@AWMAIL04.belcan.com> <27CC3060AF71DA40A5DC85F7D5B70F38011854E6@AWMAIL04.belcan.com> <86380fd30802181016i4f1a0a22s9edf8cf353117b46@mail.gmail.com> Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F38026E5FB8@AWMAIL04.belcan.com> Dan, I have been working with examples within the Scipy and Numpy framework. Those are the examples that I have been working with at this time, including the FFT example. The following command: python setup.py install. Is what I did within the Python IDLE environment. However, python was not able to see this script file. Under directory should the MyHDL folder be located?? What I mean by this, should the MyHDL folder be installed in the same directory as where the Scipy folder is located?? If I am not making any sense, please inform me as soon as possible. Thank you for your help. Respectfully, David Blubaugh ________________________________ From: Dan Fabrizio [mailto:dfabrizio51 at gmail.com] Sent: Monday, February 18, 2008 1:17 PM To: Blubaugh, David A. Subject: Re: Question Hi David, I didn't have any problems with the install on Linux and Mac OS X. Both use python 2.5 python setup.py install. Can you tell me more about the problem you are having? Did you get the basic install to work? Did you try any of the examples? Dan On Feb 18, 2008 12:54 AM, Blubaugh, David A. wrote: Dan, I am just a little bit curious as to how you installed MyHDL on your Linux machine?? Apparently, I am starting to believe that there are missing files in my installation for windows. Especially, my setup.py file may not be operational within windows. I have not received word from Mr. Decaluwe regarding any thoughts on a combined Scipy/MyHDL hybrid system. There is some internet mail list activity still occuring within the MyHDL site. I believe I will post a message on this forum and see if anyone will respond!! Also, there might be a new member in helping us, in addition to the moderate amount of help from Bill Hart. Thanks for all the help. David Blubaugh -----Original Message----- From: Blubaugh, David A. Sent: Fri 2/15/2008 5:56 PM To: 'Dan Fabrizio'; 'Dan Fabrizio' Subject: For your information -----Original Message----- From: Blubaugh, David A. Sent: Fri 2/15/2008 5:56 PM To: 'Dan Fabrizio'; 'Dan Fabrizio' Subject: For your information Dan, This is for your information. I am going to work more this weekend to see if there is a concern with python 2.5 with MyHDL. David -----Original Message----- From: Guilherme Polo [mailto:ggpolo at gmail.com] Sent: Friday, February 15, 2008 5:33 PM To: Blubaugh, David A.; python-list at python.org Subject: Re: scary thought for consideration 2008/2/15, Blubaugh, David A. : > > > > To All, > > > I am wondering as far as the integration of MyHDL with Python 2.5, if > there might be any potential version incompatibility issues? What I > mean is will MyHDL not operate correctly, if it is executed with a > Python 2.5 version not a Python 2.4? I will be testing to see if this > possibility is indeed true over the weekend. > That depends on how "custom" your project is. Take Zope for example, a lot of effort is being done to make it run under python 2.5. Having a good test suite ready would be a good way to determine if it runs correctly under python 2.5. > > Thanks, > > David Blubaugh > > This e-mail transmission contains information that is confidential and may > be privileged. It is intended only for the addressee(s) named above. If > you receive this e-mail in error, please do not read, copy or > disseminate it in any manner. If you are not the intended recipient, > any disclosure, copying, distribution or use of the contents of this > information is prohibited. Please reply to the message immediately by > informing the sender that the message was misdirected. After replying, > please erase it from your computer system. Your assistance in correcting this error is appreciated. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at cheimes.de Wed Feb 20 12:01:01 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 20 Feb 2008 18:01:01 +0100 Subject: threaded http server In-Reply-To: <910313af0802200845p46970afas5a368dc9c3c80a05@mail.gmail.com> References: <910313af0802200417if1e6422p47ca1a22cb23c8ac@mail.gmail.com> <910313af0802200845p46970afas5a368dc9c3c80a05@mail.gmail.com> Message-ID: <47BC5CCD.8080905@cheimes.de> bharath venkatesh wrote: > hi, > will this twisted,turbo gear etc help me to create a http server that can > serve multiple clients concurrently.... > and also the http server which i want to create in my project will not be > doing any IO (it is not like frontend and backend ).. but it will act as a > image_proxy_server i.e when a client wants an image it will do a http > request to my http server if the image is present in cache it will fetch it > directly from cache and return it to the client as an http reponse > otherwise it fetch from www and store it cache and also return it to > the client as an http response so basically i want to serve many clients > concurrently in fast n efficient manner You are reading data from a network socket (IO), you are serving images from a disk cache or memory cache (IO) or you are retrieving images from a remote site (IO). Your application is most certainly not using the CPU much. All you do is serving data or reading data - input and output - IO. :) Christian From python.list at tim.thechases.com Wed Feb 27 17:40:04 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 27 Feb 2008 16:40:04 -0600 Subject: Making string-formatting smarter by handling generators? In-Reply-To: <47C5CAFC.2030808@tim.thechases.com> References: <47C58E95.1030000@tim.thechases.com> <47C5CAFC.2030808@tim.thechases.com> Message-ID: <47C5E6C4.70100@tim.thechases.com> >> Note that your problem has nothing to do with map itself. >> String interpolation using % requires either many individual >> arguments, or a single *tuple* argument. A list is printed >> as itself. Just as an exercise to understand this better, I've been trying to figure out what allows for this interpolation. It doesn't seem to be via duck-typing: >>> # what does a tuple have that a list doesn't >>> tuple_set = set(dir(tuple())) >>> list_set = set(dir(list())) >>> tuple_set - list_set set(['__getnewargs__']) class LikeATuple(list): def __getnewargs__(self, *args, **kwargs): pass # now have everything dir(tuple()) has f = LikeATuple((1,2,3)) print "%s, %s, %s" % f However, if I create a class that derives from a tuple(), it seems to work fine: class MyTuple(tuple): pass f = MyTuple((1,2,3)) print "%i, %i, %i" % f it works fine. Is there some secret attribute that I'm missing? Or does string expansion absolutely require a descendent of tuple? This seems contrary to Python's ethos of duck-typing/EAFP as this requires a static type and does LBYL...which would contribute to my previous confusion. However, with dictionary lookup, it doesn't care that it's a dict, just that it implements the __getitem__ interface: class Foo(object): def __getitem__(self, name): return name.encode('rot13') f = Foo() print "%(hello)s, %(there)s, %(world)s" % f Can anybody offer insight into why one is unchangeably based off the object-hierarchy, while the other is based off duck-typing? trying-to-wrap-my-head-around-it'ly yers, -tkc From kay.schluehr at gmx.net Mon Feb 4 12:26:29 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Mon, 4 Feb 2008 09:26:29 -0800 (PST) Subject: Project naming suggestions? References: Message-ID: <64a31615-aebd-4a25-959f-b10017b3e1f2@u10g2000prn.googlegroups.com> On Feb 3, 7:17 pm, miller.pau... at gmail.com wrote: > I'm considering writing a little interpreter for a python-like > language and I'm looking for name suggestions. :-) > > Basically, I don't want to change a whole lot about Python. In fact, > I see myself starting with the compiler module from Python 2.5 and > building from there. > > This language would be more or less "Python modulo a few > (incompatible) changes, but it'd be recognizable by Python > programmers. I'm talking about stuff like "allowing the character '?' > in identifier names," and "a better way to express 'for dummy in > xrange (n):' when the index isn't needed." I'd also like to > implement most of the planned Python 3000 changes. > > Any suggestions? I'm thinking "Ophidian," for the snake connection, > or, possibly, "Circus," from "Monty Python's Flying Circus." > > Thanks :-) What about "Argh!". Sounds like Paul Grahams Arc but is more Monty Pythonesque than "Circus". From grante at visi.com Sun Feb 10 19:05:56 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 11 Feb 2008 00:05:56 -0000 Subject: Turn off ZeroDivisionError? References: <63d2e7d1-aa26-4ddc-9d12-42ae636104c1@s37g2000prg.googlegroups.com> <13qunlu5nrva731@corp.supernews.com> <877ihc5sv4.fsf@benfinney.id.au> Message-ID: <13qv4b43abncs72@corp.supernews.com> On 2008-02-10, Ben Finney wrote: > Mark Dickinson writes: >>> platform does". platforms do exactly what I want for division >>> by zero: they generate a properly signed INF. ?Python chooses >>> to override that (IMO correct) platform behavior with >>> something surprising. Python doesn't generate exceptions for >>> other floating point "events" -- why the inconsistency with >>> divide by zero? >> >> But not everyone wants 1./0. to produce an infinity; some >> people would prefer an exception. > > Special cases aren't special enough to break the rules. > > Most people would not want this behaviour either:: > > >>> 0.1 > 0.10000000000000001 > > But the justification for this violation of surprise is > "Python just does whatever the underlying hardware does with > floating-point numbers". If that's the rule, it shouldn't be > broken in the special case of division by zero. My feelings exactly. That's the rule that's always quoted to people asking about various FP weirdness, but apparently the rule only applies when/where certain people feel like it. -- Grant Edwards grante Yow! YOW!! I'm in a very at clever and adorable INSANE visi.com ASYLUM!! From senthilind at gmail.com Thu Feb 14 03:30:34 2008 From: senthilind at gmail.com (senthilind at gmail.com) Date: Thu, 14 Feb 2008 00:30:34 -0800 (PST) Subject: View life as a continuous learning experience. Message-ID: View life as a continuous learning experience. http://smallbusinessebooks.googlepages.com/ http://smallbusiness-ebooks.blogspot.com/ From joelcarrier at gmail.com Thu Feb 21 15:34:28 2008 From: joelcarrier at gmail.com (joelcarrier at gmail.com) Date: Thu, 21 Feb 2008 12:34:28 -0800 (PST) Subject: how to flush child_stdin Message-ID: <9b20c22e-db97-40bf-802a-f0f959b82c61@p43g2000hsc.googlegroups.com> I'm opening up a subprocess like this where slave.py is a text based app that receives commands and responds with output: r, w, e = popen2.popen3('python slave.py') I need to send slave.py a command and see the output, so I'll do something like: w.write("command here") then i'll try this: w.flush() A separate thread is reading from r to retrieve output of slave.py. The problem is that slave.py doesn't seem to receive commands unless I also do: w.close() But I don't want to do this because I'll want to send more commands. Any idea what is going on? From ron.duplain at gmail.com Thu Feb 28 22:41:33 2008 From: ron.duplain at gmail.com (Ron DuPlain) Date: Thu, 28 Feb 2008 19:41:33 -0800 (PST) Subject: Problems Generating HTML With pydoc References: Message-ID: On Feb 26, 3:23 am, "Juha S." wrote: > Hi, > > I'm trying to generate HTML docs for a Python package (directory) > currently containing an empty __init__.py and a Module.py file with some > classes and docstrings. I tried using the command > "F:\path\to\project\pydoc.py -w myPackage" at the Vista command prompt, > and I get "wrote myPackage.html" as output, but when I open the .html in > Firefox, I cannot navigate to the doc page of Module although it is > displayed as a link on the main page. I get a File Not Found message in > the browser for doing so. > I also expected "pydoc -w mypackage" to recursively generate html for the whole package, but it only wrote the top-level file for me as well (on Linux, for the record). > If I'm at C:\ in the command prompt and try "pydoc.py -w > F:\path\to\project\myPackage" I get "no Python documentation found for > 'Module'". > I use the workaround: pydoc -w ./ This runs "pydoc -w" on all Python files in the current directory and its subdirectories. On Windows, you'll probably have to use: pydoc -w .\ ... or "F:\path\to\project\pydoc.py -w .\" You can simplify this in Windows by adding the directory containing pydoc.py to the PATH environment variable, and by adding .PY to PATHEXT. Doing so should allow you to call just "pydoc" from the Windows command prompt (without "F:\...\pydoc.py"). Be sure to start a new command prompt after changing these environment settings. > pydoc -g seems to display the package's doc .htmls with no problems. I > can't seem to figure what's wrong here, so any help is appreciated. Yes, pydoc -g worked just fine for me before trying this workaround. If you'd like some more information, I created a pydoc example which you can browse/download. It also serves as an example of my interpretation of "Style Guide for Python Code" (PEP 8) and "Docstring Conventions" (PEP 257), both of which provide excellent guidelines for generating meaningful pydoc files. http://www.cv.nrao.edu/~rduplain/pydoc/ http://www.cv.nrao.edu/~rduplain/pydoc/README I hope this helps, Ron -- Ron DuPlain http://www.linkedin.com/in/rduplain From gherron at islandtraining.com Fri Feb 1 01:14:49 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 31 Jan 2008 22:14:49 -0800 Subject: dict comprehension In-Reply-To: <034401c86498$8e67c0f0$0203a8c0@MOUSE> References: <034401c86498$8e67c0f0$0203a8c0@MOUSE> Message-ID: <47A2B8D9.8050801@islandtraining.com> Ryan Ginstrom wrote: >> On Behalf Of Daniel Fetchinson >> What does the author mean here? What's the Preferably One Way >> (TM) to do something analogous to a dict comprehension? >> > > I imagine something like this: > > >>>> keys = "a b c".split() >>>> values = [1, 2, 3] >>>> D = dict([(a, b) for a, b in zip(keys, values)]) >>>> D >>>> > {'a': 1, 'c': 3, 'b': 2} > > Regards, > Ryan Ginstrom > > This fine example uses list comprehension to build a list of tuples which is than read by the dict builtin to create a dictionary. You can dispense with the intermediate list if you use a generator expression directly as input to the dict builtin. (Requires Python 2.4 or later.) Like this: >>> keys = "a b c".split() >>> values = [1, 2, 3] >>> D = dict((a, b) for a, b in zip(keys, values)) >>> D {'a': 1, 'c': 3, 'b': 2} >>> From luismgz at gmail.com Wed Feb 6 16:59:25 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M._Gonz=E1lez?=) Date: Wed, 6 Feb 2008 13:59:25 -0800 (PST) Subject: Is there a way to use .NET DLL from Python References: <85706ba0-8c24-4324-9a79-98c97fc802db@e4g2000hsg.googlegroups.com> Message-ID: <6c2845aa-aec5-4b75-852a-551b9cd1d6ab@f10g2000hsf.googlegroups.com> On Feb 6, 6:27 pm, Huayang Xia wrote: > Hello All, > > I have several .NET DLL (I have no source code for them), is there > anyway to use them from python instead of from C#. > > Thanks, > Huayang I used to put my .dll files into the .DLL folder, so I could simply import them as I would with any other python module. But since I started using Ironpython 2.0 Alpha* this doesn't work anymore... Any hint? Luis From stefan_ml at behnel.de Thu Feb 7 05:03:12 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 07 Feb 2008 11:03:12 +0100 Subject: Why not a Python compiler? In-Reply-To: <28eead2f-a40c-414b-bd3d-a941f8a851a2@d70g2000hsb.googlegroups.com> References: <28eead2f-a40c-414b-bd3d-a941f8a851a2@d70g2000hsb.googlegroups.com> Message-ID: <47AAD760.5030504@behnel.de> Santiago Romero wrote: > I'm impressed with python. I'm very happy with the language and I > find Python+Pygame a very powerful and productive way of writing 2D > games. I'm not, at this moment, worried about execution speed of the > small game I'm working on (it runs at full 60 fps even in an old AMD- > K6 450 Laptop computer), but I continue asking me the same question: > > Why not a Python COMPILER? > > It would be very nice to be able to output Linux, MAC or Windows > binaries of compiled (not bytecompiled) code. It would run faster, it > will be smaller in size (I think) Take a look at Cython. It's an optimising Python-to-C compiler for writing Python extensions. So you can basically take a Python module and compile it to C code that runs against the CPython runtime. http://cython.org/ > and it will be easy to distribute to > people not having python installed. Yes, I know about py2exe, but I'm > not sure if that's the right aproach. That's a different focus, but then, there's "portable Python". http://www.portablepython.com/ Stefan From ali_292000 at yahoo.com Thu Feb 14 20:01:14 2008 From: ali_292000 at yahoo.com (silkenpy) Date: Thu, 14 Feb 2008 17:01:14 -0800 (PST) Subject: Please help help ..... for threading Message-ID: <15492998.post@talk.nabble.com> Hi, please help me to find a solution to run this program correctlly or tell me my basic mistake. import thread import threading import time from jpype import * def sleepFunction(): print"ya ali" classpath = "-Djava.class.path=praat.jar" startJVM(getDefaultJVMPath(),"-ea",classpath) Formant=JPackage("praat").Formant s=Formant("iia-001-000.Formant") w=s.getF2_frequency() print w shutdownJVM() for i in range(1): thread.start_new_thread(sleepFunction, ()) time.sleep(1) print "goodbye!" The result is ya ali ya ali Unhandled exception in thread started by Traceback (most recent call last): File "C:\Downloads\_extracted\py_threading.zip.extracted\py_threading\sle.py", line 19, in sleepFunction startJVM(getDefaultJVMPath(),"-ea",classpath) File "D:\Python25\Lib\site-packages\jpype\_core.py", line 43, in startJVM _jpype.startup(jvm, tuple(args), True) RuntimeError: Unable to start JVM at src/native/common/jp_env.cpp:54 Unhandled exception in thread started by Traceback (most recent call last): File "C:\Downloads\_extracted\py_threading.zip.extracted\py_threading\sle.py", line 19, in sleepFunction startJVM(getDefaultJVMPath(),"-ea",classpath) File "D:\Python25\Lib\site-packages\jpype\_core.py", line 43, in startJVM _jpype.startup(jvm, tuple(args), True) RuntimeError: Unknown Exception goodbye! Thanks a lot. -- View this message in context: http://www.nabble.com/Please-help-help-.....-for-threading-tp15492998p15492998.html Sent from the Python - python-list mailing list archive at Nabble.com. From castironpi at gmail.com Mon Feb 25 22:30:08 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 25 Feb 2008 19:30:08 -0800 (PST) Subject: is there enough information? Message-ID: Specify def thloop( th ): while th.cont: with th.step[2]: th.ret= th.cmd+ 1 def acq( th ): with th.step[1]: th.cmd= 100 with th.step[3]: ret1= th.ret th.step.reset() assert ret1== 101 Is it enough? From bignose+hates-spam at benfinney.id.au Wed Feb 27 02:03:31 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 27 Feb 2008 18:03:31 +1100 Subject: Documentation - which format References: <0001HW.C3EA559A00413F8FB01AD9AF@news.individual.de> <87k5krdmtc.fsf@benfinney.id.au> <0001HW.C3EAC18C0045A69FB01AD9AF@news.individual.de> Message-ID: <8763waev98.fsf@benfinney.id.au> Jumping Arne writes: > On Wed, 27 Feb 2008 05:51:11 +0100, Ben Finney wrote > (in article <87k5krdmtc.fsf at benfinney.id.au>): > > > Your needs are met amply with reStructuredText. It's still under > > active development > > is http://docutils.sourceforge.net/ still the official site (I > didn't find anything else) Yes, TTBOMK. The site hasn't been updated for a while, but I follow the mailing list and activity continues on the code itself. -- \ ?Holy hole in a donut, Batman!? ?Robin | `\ | _o__) | Ben Finney From jstroud at mbi.ucla.edu Wed Feb 13 03:54:36 2008 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 13 Feb 2008 00:54:36 -0800 Subject: Big time WTF with generators - bug? In-Reply-To: <7x3arxckol.fsf@ruckus.brouhaha.com> References: <7x3arxckol.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > James Stroud writes: >> I defined a little debugging function called iterprint: >> >> def iterprint(thing): ... >> for x in thing: >> iterprint(x) > > of course this mutates the thing that is being printed. Try using > itertools.tee to fork a copy of the iterator and print from that. > I didn't look at the rest of your code enough to spot any errors > but take note of the warnings in the groupby documentation about > pitfalls with using the results some number of times other than > exactly once. Thank you for your answer, but I am aware of this caveat. Something is consuming my generator *before* I iterprint it. Please give it another look if you would be so kind. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From johnwalker3301 at comcast.net Tue Feb 5 12:30:28 2008 From: johnwalker3301 at comcast.net (jpw) Date: Tue, 5 Feb 2008 09:30:28 -0800 (PST) Subject: Need help porting a C++ / Python Embedded app to multiple platforms Message-ID: <1b72adf5-7a90-421e-a336-755acb5faedf@i7g2000prf.googlegroups.com> I am writing a Python / C++ embed app and it need to work on 3 platforms I have the PYTHONPATH variable set correctly and have gone back and downloaded compiled and installed the latest Python 2.5.1 on Solaris and Linux. adding in the --enable-shared when running the ./ configure ... file Mac - good to go there was no need do anything except update to 2.5 and add the PYTHONPATH Solaris 10 - Linux - Errors occur in the same point at runtime as soon as I try to do load a module The load module code is as follows: PyObject* name = PyString_FromString(moduleName.c_str()); PyObject* mModule = PyImport_Import(name); Py_DECREF(name); if (mModule == 0) { std::ostringstream oss; oss << "Failed to load module <" << moduleName << ">"; throw PythonException(oss.str()); } both errors indicate a problem with libc.so LINUX error stacktrace: terminate called after throwing an instance of 'PythonWrapper::PythonException' what(): N13PythonWrapper15PythonExceptionE Program received signal SIGABRT, Aborted. [Switching to Thread 1161832800 (LWP 16508)] 0x00000033f332e21d in raise () from /lib64/tls/libc.so.6 (gdb) where #0 0x00000033f332e21d in raise () from /lib64/tls/libc.so.6 #1 0x00000033f332fa1e in abort () from /lib64/tls/libc.so.6 #2 0x0000002a96360a20 in __gnu_cxx::__verbose_terminate_handler () at ../../../../gcc-4.0.4/libstdc++-v3/libsupc++/vterminate.cc:97 #3 0x0000002a9635ea66 in __cxxabiv1::__terminate (handler=0x405f) at ../../../../gcc-4.0.4/libstdc++-v3/libsupc++/eh_terminate.cc:43 #4 0x0000002a9635ea93 in std::terminate () at ../../../../gcc-4.0.4/libstdc++-v3/libsupc++/eh_terminate.cc:53 #5 0x0000002a9635eb7a in __cxa_throw (obj=, tinfo=, dest=) at ../../../../gcc-4.0.4/libstdc++-v3/libsupc++/eh_throw.cc:77 #6 0x00000000005bb73d in PythonWrapper::Python::loadModule (this=0x94f080, moduleName=@0x45401f90) at PythonWrapper.C:425 SOLARIS call stack: Program received signal SIGABRT, Aborted. [Switching to LWP 12] 0xfe7412a4 in _lwp_kill () from /usr/lib/libc.so.1 (gdb) where #0 0xfe7412a4 in _lwp_kill () from /usr/lib/libc.so.1 #1 0xfe6dfe20 in raise () from /usr/lib/libc.so.1 #2 0xfe6c0040 in abort () from /usr/lib/libc.so.1 #3 0xfe92e64c in __gnu_cxx::__verbose_terminate_handler () at ../../../../gcc-4.0.4/libstdc++-v3/libsupc++/vterminate.cc:97 #4 0xfe92bfd8 in __cxxabiv1::__terminate ( handler=0xfe92e438 <__gnu_cxx::__verbose_terminate_handler()>) at ../../../../gcc-4.0.4/libstdc++-v3/libsupc++/eh_terminate.cc:43 #5 0xfe92c028 in std::terminate () at ../../../../gcc-4.0.4/libstdc++-v3/libsupc++/eh_terminate.cc:53 #6 0xfe92c18c in __cxa_throw (obj=, tinfo=0x3a3568, dest=0x272e6c <~PythonException>) at ../../../../gcc-4.0.4/libstdc++-v3/libsupc++/eh_throw.cc:77 #7 0x0027422c in PythonWrapper::Python::loadModule (this=0x46bc48, moduleName=@0xf5cffb10) at PythonWrapper.C:425 Any help would be greatly appreciated, jpw From paddy3118 at googlemail.com Fri Feb 1 00:01:27 2008 From: paddy3118 at googlemail.com (Paddy) Date: Thu, 31 Jan 2008 21:01:27 -0800 (PST) Subject: Python Standardization: Wikipedia entry References: <4dc87a25-1d90-4b66-8fa4-d0d41f48344e@i29g2000prf.googlegroups.com><479f562c$0$36342$742ec2ed@news.sonic.net> <47a251e7$0$36328$742ec2ed@news.sonic.net> Message-ID: <9f54ffca-fcb7-47b4-abba-d8e3e96b863c@v4g2000hsf.googlegroups.com> On Feb 1, 12:18 am, "Terry Reedy" wrote: > "John Nagle" wrote in message > > news:47a251e7$0$36328$742ec2ed at news.sonic.net.. > > > Submitting Python 2.5 to ISO/ANSI might be a good idea. > > ANSI does not actually make standards. It make metastandards about how to > make standards (both style and process) and accredites US standard-making > bodies that will follow those metastandards. The processes require > committee meetings and public comment periods -- a few years and some $$$. > There in no guarantee that what would come out of such a process would be > what went in, so 'Standard Python' might easily be a language with no > implementations. > > ANSI standards are owned by ANSI or perhaps the accrediting body. In any > case, electronic copies sell for $30. They cannot legally be accessed free > as for the docs at python.org. HI Terry, Is their a standardizing body out their to `legitimise` open source languages like Python? - Paddy. From jeff at schwabcenter.com Thu Feb 21 13:15:43 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Thu, 21 Feb 2008 10:15:43 -0800 Subject: newbie in python In-Reply-To: <1d24edf1-78f1-420e-9ca5-ef7e810e20cc@72g2000hsu.googlegroups.com> References: <1d24edf1-78f1-420e-9ca5-ef7e810e20cc@72g2000hsu.googlegroups.com> Message-ID: ctechnician at gmail.com wrote: > I'm very interesed to learn python and really willing to do so,but > unfortunately dont know where to start, or what programs need to > install to start. There are several good replies already on this thread, but in case any experienced programmers searching the Google archives are looking for the fastest way to learn Python, I highly recommend Python in a Nutshell by Alex Martelli (O'Reilly). Good tutorial, high information density, avoids hand-waving, solid reference. Do *not* bother with Programming Python until you have some experience with the core language. I don't know why O'Reilly called it that, except to mislead people into thinking it was similar to the highly successful Programming Perl; if so, I fell for it, and so did plenty of other people (so there's probably a copy in your coworker's office already). Programming Python is (despite its size) the moral equivalent of the O'Reilly "Cookbooks" for other languages. It's not necessarily a bad book, but the only language/library tutorial it gives is meant to be a review, not an introduction. From steve at REMOVE-THIS-cybersource.com.au Thu Feb 7 16:27:33 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 07 Feb 2008 21:27:33 -0000 Subject: Why not a Python compiler? References: <28eead2f-a40c-414b-bd3d-a941f8a851a2@d70g2000hsb.googlegroups.com> <81339c25-f9b6-47a1-941e-8ae39c35773c@e6g2000prf.googlegroups.com> <98a1bc2d-290b-4b6d-8a3d-eda7666d2b8b@l1g2000hsa.googlegroups.com> Message-ID: <13qmtu5j1b1p6a2@corp.supernews.com> On Thu, 07 Feb 2008 09:06:32 -0500, Steve Holden wrote: > Ryszard Szopa wrote: >> On Feb 5, 9:30 am, cokofree... at gmail.com wrote: >> >>> I don't know the exact details but I think the issue is the dynamic >>> nature of Python makes it impossible to correctly store the various >>> types and changes into compiled code. Someone else will probably be >>> able to provide a good reason as to why it isn't very feasible, nor a >>> good idea. If you want to speed up your python look at Psyco. >>> http://psyco.sourceforge.net/ >> >> Yeah, but exactly what features make it so hard to write a compiler for >> Python? >> [...] > > a. People tell me writing a compiler for Python is hard. > > b. It's certainly way to hard for me. > > c. But hey, I've heard about this neat language called Common Lisp that > has a compiler. It looks a lot like Python. > > d. So why can't you brainboxes write a compiler for Python? > > Please tell me if I'm missing anything from this summary of your thought > processes. Be fair -- he's asking what specific features of Python make it hard. That's a reasonable question. -- Steven From bockman at virgilio.it Mon Feb 25 07:19:00 2008 From: bockman at virgilio.it (bockman at virgilio.it) Date: Mon, 25 Feb 2008 04:19:00 -0800 (PST) Subject: network programming: how does s.accept() work? References: <6d564fca-3884-4665-8a86-f7e658217a33@e60g2000hsh.googlegroups.com> <446482ef-1fd8-41dc-a8fd-44de8b51a8e8@o10g2000hsf.googlegroups.com> <379fcee4-15e0-48c2-863b-4b7458893cbe@h25g2000hsf.googlegroups.com> Message-ID: <8001c14d-efad-4c97-af97-64853609738a@q33g2000hsh.googlegroups.com> > > The question I'm really trying to answer is: if a client connects to a > host at a specific port, but the server changes the port when it > creates a new socket with accept(), how does data sent by the client > arrive at the correct port? ?Won't the client be sending data to the > original port e.g. port 5052 in the client code above? > I'm not an expert, never used TCP/IP below the socket abstraction level, but I imagine that after accept, the client side of the connection is someow 'rewired' with the new socket created on the server side. Anyhow, this is not python-related, since the socket C library behaves exactly in the same way. Ciao ----- FB From debl2NoSpam at verizon.net Sat Feb 23 01:37:38 2008 From: debl2NoSpam at verizon.net (David Lees) Date: Sat, 23 Feb 2008 06:37:38 GMT Subject: Looking for suggestions on improving numpy code Message-ID: I am starting to use numpy and have written a hack for reading in a large data set that has 8 columns and millions of rows. I want to read and process a single column. I have written the very ugly hack below, but am sure there is a more efficient and pythonic way to do this. The file is too big to read by brute force and select a column, so it is read in chunks and the column selected. Things I don't like in the code: 1. Performing a transpose on a large array 2. Uncertainty about numpy append efficiency Is there a way to directly read every n'th element from the file into an array? david from numpy import * from scipy.io.numpyio import fread fd = open('testcase.bin', 'rb') datatype = 'h' byteswap = 0 M = 1000000 N = 8 size = M*N shape = (M,N) colNum = 2 sf =1.645278e-04*10 z=array([]) for i in xrange(50): data = fread(fd, size, datatype,datatype,byteswap) data = data.reshape(shape) data = data.transpose() z = append(z,data[colNum]*sf) print z.mean() fd.close() From arnodel at googlemail.com Mon Feb 18 07:26:10 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 18 Feb 2008 04:26:10 -0800 (PST) Subject: Seemingly odd 'is' comparison. References: <47b36135$0$26076$88260bb3@free.teranews.com> Message-ID: <5cc4c9b1-110d-4a6f-9e8f-d67e2456c20b@n58g2000hsf.googlegroups.com> On Feb 13, 10:19?pm, Tobiah wrote: > >>> print float(3.0) is float(3.0) > True > >>> print float(3.0 * 1.0) is float(3.0) > False [You don't need to wrap your floats in float()] >>> def f(): ... return 3.0 is 3.0, 3.0*1.0 is 3.0 ... >>> f() (True, False) >>> import dis >>> dis.dis(f) 2 0 LOAD_CONST 1 (3.0) 3 LOAD_CONST 1 (3.0) 6 COMPARE_OP 8 (is) 9 LOAD_CONST 3 (3.0) 12 LOAD_CONST 1 (3.0) 15 COMPARE_OP 8 (is) 18 BUILD_TUPLE 2 21 RETURN_VALUE As you can see when "3.0 is 3.0" is evaluated the same float object is put on the stack twice so the 'is' comparison is True (LOAD_CONST 1 / LOAD_CONST 1 / COMPARE_OP 8). Whereas when "3.0*1.0 is 3.0" is evaluated, *two* different float objects are put on the stack and compared (LOAD_CONST 3 / LOAD_CONST 1 / COMPARE_OP 8). Therefore the result is False. HTH -- Arnaud From aahz at pythoncraft.com Thu Feb 21 08:25:58 2008 From: aahz at pythoncraft.com (Aahz) Date: 21 Feb 2008 05:25:58 -0800 Subject: Globals or objects? References: <72b59db8-ec9c-480a-9ae7-92a69acb70a6@41g2000hsc.googlegroups.com> Message-ID: In article <72b59db8-ec9c-480a-9ae7-92a69acb70a6 at 41g2000hsc.googlegroups.com>, wrote: > >I had a global variable holding a count. One source Google found >suggested that I wouldn't need the global if I used an object. So I >created a Singleton class that now holds the former global as an >instance attribute. Bye, bye, global. > >But later I thought about it. I cannot see a single advantage to the >object approach. Am I missing something? Or was the original global a >better, cleaner solution to the "I need a value I can read/write from >several places" problem? The advantage of the global singleton is that it is a container; therefore, its contents are mutable and you don't need to keep using the ``global`` statement. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "All problems in computer science can be solved by another level of indirection." --Butler Lampson From bearophileHUGS at lycos.com Wed Feb 6 09:42:38 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 6 Feb 2008 06:42:38 -0800 (PST) Subject: Data Manipulation - Rows to Columns References: Message-ID: <05fd0f0a-d801-4ba9-b3d0-6bca676b5354@e10g2000prf.googlegroups.com> This is smells of homework. Here are few alternative solutions of mine that I don't like. I presume a good teacher will refuse them all, because no one of them uses the right tool :-) And every one of them has some small problem (even if they work here). data = """\ TABLE black blue red CHAIR yellow black red SOFA white gray pink """ data2 = data.replace("","").replace("","").replace("","") groups = [b.split() for b in data2.split("") if b] print groups print import re data2 = re.sub(r"||", "", data) groups = [b.split() for b in data2.split("") if b] print groups print import re def splitter(data): patt = re.compile(r"(?:(.*))|(?:(.*))") parts = [] for mo in patt.finditer(data): p1, p2 = mo.groups() if p1 is None: parts.append(p2) else: if parts: yield parts parts = [p1] if parts: yield parts print list(splitter(data)) print def splitter2(items, predicate): parts = [] for el in items: if predicate(el): parts.append(el) else: if parts: yield parts parts = [el] if parts: yield parts import re patt = re.compile(r"(?:(.*))|(?:(.*))") xmobjects = (mo.groups() for mo in patt.finditer(data)) process = lambda group: [group[0][0]] + [part[1] for part in group[1:]] isstart = lambda (p1,p2): p1 is None xgroups = (process(g) for g in splitter2(xmobjects, isstart)) print list(xgroups) print data2 = """ TABLE black blue< / color> red CHAIR yellow black red SOFA white gray < color > pink < / color > """ import re patt = re.compile(r""" \s* < \s* (item|color) \s* > \s* (.*) \s* < \s* / \s* (?:table|color) \s* > \s* """, re.VERBOSE) groups = [] for mo in patt.finditer(data2): p1, p2 = mo.groups() if p1 == "item": groups.append([p2]) else: groups[-1].append(p2) print groups print Bye, bearophile From pavlovevidence at gmail.com Wed Feb 27 07:00:29 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 27 Feb 2008 04:00:29 -0800 (PST) Subject: __getattribute__ meta class? References: <13s6v6fqagooab@corp.supernews.com> <13s9u5bp55h6k0a@corp.supernews.com> Message-ID: On Feb 27, 12:44 am, "bambam" wrote: > In retrospect, the project has three parts: remove > side effects, push side effects to a common location, modify code so that > changes only affect areas that encapsulate side effects. This code allows > top level code to pretend that the intermediate code has not changed. Gah. Libraries that "helpfully" do things on behalf of the user strike again, and the mess bambam posted is what you have to do to disable these "helpful" effects. I'll grant that it's possible that the library wasn't trying to be helpful and was just indicriminately letting side effects loose. Shame on the writer in any case. Carl Banks From steve at REMOVE-THIS-cybersource.com.au Thu Feb 7 16:30:44 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 07 Feb 2008 21:30:44 -0000 Subject: beginners help References: <47aaffb2$0$85781$e4fe514c@news.xs4all.nl> Message-ID: <13qmu44hh60ced9@corp.supernews.com> On Thu, 07 Feb 2008 13:53:48 +0100, Guido van Brakel wrote: > Hello > > I totally new to python and i'm doing a python course now. Maybe someone > could help me a little bit here: > > I need to create this script. > > If i enter a center digit like 5 for example i need to create two > vertical and horzitonal rows that looks like this. If i enter 6 it shows > 6 six starts. How can i do this, because i don't have any clue. > > ***** > * * > * * > * * > ***** Start by writing some Python code that draws a horizontal line of stars. (Hint: "print '*' draws one star.) Now write some code that draws a column of stars. Now combine them to draw a square. Come back when you have some more specific questions. Regards, -- Steven From JKPeck at gmail.com Fri Feb 1 13:04:18 2008 From: JKPeck at gmail.com (JKPeck) Date: Fri, 1 Feb 2008 10:04:18 -0800 (PST) Subject: Mysterious xml.sax Encoding Exception Message-ID: <6edad0b6-1d4a-46ec-a6c2-c8caed3089c3@f47g2000hsd.googlegroups.com> I have a module that uses xml.sax and feeds it a string of xml as in xml.sax.parseString(dictfile,handler) The xml is always encoded in utf-16, and the XML string always starts with This almost always works fine, but two users of this module get an exception whatever input they use it on. (The actual xml is generated by an api in our application that returns an xml version of metadata associated with the application's data.) The exception is xml.sax._exceptions.SAXParseException: :1:30: encoding specified in XML declaration is incorrect. In both of these cases, there are only plain, 7-bit ascii characters in the xml, and it really is valid utf-16 as far as I can tell. Now here is the hard part: This never happens to me, and having gotten the actual xml content from one of the users and fed it to the parser, I don't get the exception. What could be going on? We are all on Python 2.5 (and all on an English locale). Any suggestions would be appreciated. -Jon Peck From nicola.musatti at gmail.com Fri Feb 22 07:48:28 2008 From: nicola.musatti at gmail.com (Nicola Musatti) Date: Fri, 22 Feb 2008 04:48:28 -0800 (PST) Subject: Article of interest: Python pros/cons for the enterprise References: <2f1527a7-2f66-44c7-9665-4d8ff01fa5ab@28g2000hsw.googlegroups.com> <47bd4a24$0$25225$426a74cc@news.free.fr> <036e93e6-5840-4a3c-8642-67a0a9ec44f2@i7g2000prf.googlegroups.com> <784ec210-f389-4a15-b458-961100de9103@v3g2000hsc.googlegroups.com> <9a3f9e3c-acf5-453f-a075-e0a044b21237@p73g2000hsd.googlegroups.com> <7xwsoxdzb8.fsf@ruckus.brouhaha.com> Message-ID: On Feb 22, 12:07 pm, Paul Rubin wrote: > Nicola Musatti writes: > > In C++ memory is just another resource which you can handle just like > > any other one, possibly using RAII. > > Ok, I'll bite. Here's a straightforward Python expression: > > a = [f(x) + g(y) for x,y in izip(m1, m2) if h(x,y).frob() == 7] > > Consider how many intermediate objects are being allocated in figuring > out that listcomp. Do you REALLY want to manage all the deallocation > with something like RAII? What makes you think that a translation of a similar expression would involve explicit dynamic allocation at all? Barring bugs, here's an equivalent example: #include #include #include int f(int n) { return n * 2; } int g(int n) { return ( n * 2 ) + 1; } std::map izip(int i, int j) { std::map m; m[i] = j; m[j] = i; return m; } class A { int i, j; public: A(int ii, int jj) : i(ii), j(jj) {} int frob() { return i + j; } }; A h(int i, int j) { return A(i, j); } int main() { int m1 = 3; int m2 = 4; std::vector a; std::map m = izip(m1, m2); for ( std::map::iterator i = m.begin(); i != m.end(); ++i ) { if ( h(i->first, i->second).frob() == 7 ) a.push_back(f(i->first) + g(i->second)); } for ( std::vector::iterator i = a.begin(); i != a.end(); ++i ) std::cout << *i << '\n'; } As you can see the standard library takes care of all memory management. Cheers, Nicola Musatti From a.smith at ukgrid.net Mon Feb 4 11:51:35 2008 From: a.smith at ukgrid.net (Andy Smith) Date: Mon, 4 Feb 2008 17:51:35 +0100 Subject: Pysqlite issue no attribute 'autocommit' RESOLVED Message-ID: <011f01c8674e$388eece0$2601a8c0@computer> Ok, simple fix... Updated to MySQL_python-1.2.2 and all ok now! :D ----- Original Message ----- From: Andy Smith To: python-list at python.org Sent: Monday, February 04, 2008 3:45 PM Subject: Pysqlite issue no attribute 'autocommit' Hi there, Im trying to run a Python based program which uses MySQL with python-sqlite and Im recieving this error, 'Connection' object has no attribute 'autocommit' I?ve had a google for this and its seems like it may be a bug python-sqlite or sqlite bug , but also I tried searching for it on the python issue traker and didnt find anything. Is anyone else aware of this issue and any solution? thanks for any help! Andy. PS sorry if I didnt include much info, hoping its a known issue (and also I didnt write the code, so not sure what else to include off the top of my head! :P) -------------- next part -------------- An HTML attachment was scrubbed... URL: From carsten at uniqsys.com Wed Feb 6 16:52:05 2008 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 06 Feb 2008 16:52:05 -0500 Subject: IronPython vs CPython: faster in 1.6 times? In-Reply-To: References: <52c34392-5c5b-49b8-8c75-ba9add438b73@k39g2000hsf.googlegroups.com> <47A8BD65.2090707@behnel.de> Message-ID: <1202334725.3463.11.camel@dot.uniqsys.com> On Wed, 2008-02-06 at 13:39 -0800, Fuzzyman wrote: > On Feb 5, 7:47 pm, Stefan Behnel wrote: > > bearophileH... at lycos.com schrieb: > > > > > Mike C. Fletcher: > > >> Not sure if Mono also provides a speedup. > > > > > There is a set of good benchmarks here, the answer is negative: > > >http://shootout.alioth.debian.org/sandbox/benchmark.php?test=all?... > > > > This doesn't look like Mono to me: > > > > IronPython1.1 (1.1) on .NET 2.0.50727.42 > > > Running on Debian? Fairly unlikely. :-) Well, that *is* what the version string reports for IronPython on Mono on Linux: $ uname -sr Linux 2.6.18-1.2200.fc5smp $ mono ipy.exe IronPython 1.1 (1.1) on .NET 2.0.50727.42 Copyright (c) Microsoft Corporation. All rights reserved. -- Carsten Haese http://informixdb.sourceforge.net From deets at nospam.web.de Fri Feb 15 15:30:13 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 15 Feb 2008 21:30:13 +0100 Subject: Floating point bug? In-Reply-To: <188be6e9-bc05-4a72-924b-1de184980002@n58g2000hsf.googlegroups.com> References: <6eba298e-6888-462a-afa7-54fae02c3dce@y5g2000hsf.googlegroups.com> <61ibo1F1uqso2U1@mid.uni-berlin.de> <188be6e9-bc05-4a72-924b-1de184980002@n58g2000hsf.googlegroups.com> Message-ID: <61mb2pF1v6vh0U1@mid.uni-berlin.de> Zentrader schrieb: >> That's a misconception. The decimal-module has a different base (10 >> instead of 2), and higher precision. But that doesn't change the fact >> that it will expose the same rounding-errors as floats do - just for >> different numbers. >> >> >>> import decimal as d >> >>> d = d.Decimal >> >>> d("1") / d("3") * d("3") >> Decimal("0.9999999999999999999999999999") > > Surely you jest. Your example is exact to 28 digits. Your attempted > trick is to use a number that never ends (1/3=0.3333...). It would > only convert back to one if you have and infinite number of > significant digits. That has nothing to do with the Python decimal > module (which does what it claims). It is one of the idiosyncrasies > of the base 10 number system. Remember we are working with base 10 > decimals and not fractions. The point is that all numbering systems with a base + precision will have (rational) values they can't exactly represent. Q\R is of course out of the question by definition.... And the poster I replied to said """ This is true. Fortunately Python does provide a module which allows you to work with exact floating point quantities. """ Which is not more true for decimal as it is for IEEE754 floating points. Just for other values. Diez From aaron.watters at gmail.com Tue Feb 26 10:03:41 2008 From: aaron.watters at gmail.com (Aaron Watters) Date: Tue, 26 Feb 2008 07:03:41 -0800 (PST) Subject: Andy Pausch (of Alice fame) -- last lecture Message-ID: <99799268-e8ee-4352-8c74-83fefe6a515d@u69g2000hse.googlegroups.com> Hi folks. Andy Pausch who headed up the Alice project which aims to teach 3D animation using Python has gained additional fame from his "last lecture" where he talks about being diagnosed with terminal pancreatic cancer, and comments on life in general. http://www.cs.cmu.edu/~pausch/ You've probably already seen it, but I thought I'd point out the Python angle. It's a good view to help put things in perspective. Its one of those internet phenomena. -- Aaron Watters === http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=life+instance From python.list at tim.thechases.com Mon Feb 25 10:31:57 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 25 Feb 2008 09:31:57 -0600 Subject: Python for web... In-Reply-To: References: <983c7459-7388-41ca-a192-b39805ea0b69@s8g2000prg.googlegroups.com> <47c1bf2c$0$381$9b4e6d93@newsspool2.arcor-online.net> <563291ee-322f-4849-bca7-1b9ecbf25713@k2g2000hse.googlegroups.com> Message-ID: <47C2DF6D.4060705@tim.thechases.com> > I didn't have any trouble setting up mod_python & Django. However, I > am my own hosting provider. That may make a difference. ;-) > > I can install fastcgi if it's a big win. From my understanding, the python-code under mod_python runs as whatever Apaches runs as ("www", "wwwdata", whatever). If this doesn't matter in your deployment, then there's little reason to do anything other than stick with what you know. The advantage of fastcgi (again, from my feeble understanding) is that the fastcgi process (your python code) runs as a designated user. This allows hosting companies to have your code run as you, Pat's code run as Pat, etc. This makes separation of privs a little easier so Pat's code doesn't screw up things your environment, and your code doesn't screw up Pat's. Nothing should really stop you from running your code as "www"/"wwwdata" which would simulate the mod_python environment somewhat. It's up to you to decide the magnitude of this "big" win :) -tkc From cwitts at gmail.com Fri Feb 15 14:19:28 2008 From: cwitts at gmail.com (Chris) Date: Fri, 15 Feb 2008 11:19:28 -0800 (PST) Subject: linux disc space References: <391a2029-b800-4c82-a861-5d07bb4bec15@h11g2000prf.googlegroups.com> Message-ID: <74a05b4f-0869-4060-8115-3af0ffc59cf4@e25g2000prg.googlegroups.com> On Feb 15, 7:10 pm, DataSmash wrote: > I simply want to capture the free disc space in a variable so that I > can compare changes. I'm aware of a few commands like "df -h" or "du - > k", but I can't figure out how to capture those values as a variable. > I also looked at os.statvfs(), but that output doesn't seem to make > any sense at all to me, knowing the size of the disc. > Thanks for your help! > R.D. import os, statvfs s = os.statvfs(".") freebytes = s[statvfs.F_BSIZE] * s[statvfs.F_BAVAIL] HTH, Chris From bj_666 at gmx.net Mon Feb 4 02:55:38 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 4 Feb 2008 07:55:38 GMT Subject: Elementary string-parsing References: Message-ID: <60nunqF1ro06iU4@mid.uni-berlin.de> On Mon, 04 Feb 2008 03:21:18 +0000, Odysseus wrote: > def extract_data(): > i = 0 > while i < len(names): > name = names[i][6:] # strip off "Name: " > found[name] = {'epoch1': cells[10 * i + na], > 'epoch2': cells[10 * i + na + 1], > 'time': cells[10 * i + na + 5], > 'score1': cells[10 * i + na + 6], > 'score2': cells[10 * i + na + 7]} Here and in later code you use a ``while`` loop although it is known at loop start how many times the loop body will be executed. That's a job for a ``for`` loop. If possible not over an integer that is used later just as index into list, but the list itself. Here you need both, index and objects from `names`. There's the `enumerate()` function for creating an iterable of (index, name) from `names`. I'd put all the relevant information that describes a field of the dictionary that is put into `found` into tuples and loop over it. There is the cell name, the index of the cell and function that converts the string from that cell into an object that is stored in the dictionary. This leads to (untestet): def extract_data(names, na, cells): found = dict() for i, name in enumerate(names): data = dict() cells_index = 10 * i + na for cell_name, index, parse in (('epoch1', 0, parse_date), ('epoch2', 1, parse_date), ('time', 5, parse_number), ('score1', 6, parse_number), ('score2', 7, parse_number)): data[cell_name] = parse(cells[cells_index + index]) assert name.startswith('Name: ') found[name[6:]] = data return found The `parse_number()` function could look like this: def parse_number(string): try: return float(string.replace(',', '')) except ValueError: return string Indeed the commas can be replaced a bit more elegant. :-) `parse_date()` is left as an exercise for the reader. > for k in ('epoch1', 'epoch2'): > dlist = found[name][k].split(" ") > m = 0 > while m < 12: > if m_abbrevs[m] == dlist[1]: > dlist[1] = m + 1 > break > m += 1 > tlist = dlist[3].split(":") > found[name][k] = timegm((int(dlist[2]), int(dlist[1]), > int(dlist[0]), int(tlist[0]), > int(tlist[1]), int(tlist[2]), > -1, -1, 0)) > i += 1 > > The function appears to be working OK as is, but I would welcome any & > all suggestions for improving it or making it more idiomatic. As already said, that ``while`` loop should be a ``for`` loop. But if you put `m_abbrevs` into a `list` you can replace the loop with a single call to its `index()` method: ``dlist[1] = m_abbrevs.index(dlist[1]) + 1``. Ciao, Marc 'BlackJack' Rintsch From pboppudi at vmware.com Mon Feb 11 12:21:16 2008 From: pboppudi at vmware.com (Praveena Boppudi (c)) Date: Mon, 11 Feb 2008 09:21:16 -0800 Subject: how to find current working user Message-ID: Hi, Can anyone tell me how to find current working user in windows? Thanks, Praveena. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rcdailey at gmail.com Mon Feb 25 11:36:25 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Mon, 25 Feb 2008 10:36:25 -0600 Subject: String compare question Message-ID: <496954360802250836u162eeb49tfac382c6ef2f96a7@mail.gmail.com> Hi, Currently I have the following code: ignored_dirs = ( r".\boost\include" ) if __name__ == "__main__": # Walk the directory tree rooted at 'source' for root, dirs, files in os.walk( source ): if root not in ignored_dirs: CopyFiles( root, files, ".dll" ) else: print root Specifically take a look at the if condition checking if a string is inside of ignored_dirs. Of course this will only do substring searches, however I want to perform an exact match on this string. Is there anyway of doing this? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Feb 13 04:31:39 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 13 Feb 2008 10:31:39 +0100 Subject: Big time WTF with generators - bug? References: Message-ID: James Stroud wrote: groupby() is "all you can eat", but "no doggy bag". > def serialize(table, keyer=_keyer, > ? ? ? ? ? ? ? ? ? ? ? selector=_selector, > ? ? ? ? ? ? ? ? ? ? ? keyfunc=_keyfunc, > ? ? ? ? ? ? ? ? ? ? ? series_keyfunc=_series_keyfunc): > ? ?keyed = izip(imap(keyer, table), table) > ? ?filtered = ifilter(selector, keyed) > ? ?serialized = groupby(filtered, series_keyfunc) > ? ?serieses = [] > ? ?for s_name, series in serialized: > ? ? ?grouped = groupby(series, keyfunc) > ? ? ?regrouped = ((k, (v[1] for v in g)) for (k,g) in grouped) > ? ? ?serieses.append((s_name, regrouped)) You are trying to store a group for later consumption here. > ? ?for s in serieses: > ? ? ?yield s That doesn't work: >>> groups = [g for k, g in groupby(range(10), lambda x: x//3)] >>> for g in groups: ... print list(g) ... [] [] [] [9] You cannot work around that because what invalidates a group is the call of groups.next(): >>> groups = groupby(range(10), lambda x: x//3) >>> g = groups.next()[1] >>> g.next() 0 >>> groups.next() (1, ) >>> g.next() Traceback (most recent call last): File "", line 1, in StopIteration Perhaps Python should throw an out-of-band exception for an invalid group instead of yielding bogus data. Peter From gherzig at fmed.uba.ar Tue Feb 19 16:47:26 2008 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Tue, 19 Feb 2008 18:47:26 -0300 Subject: standardization allows? In-Reply-To: <2be7ece0-87b5-4298-a68c-11408551e25b@71g2000hse.googlegroups.com> References: <14d20e7f-78a6-4b93-b784-f7f5b58de471@c23g2000hsa.googlegroups.com> <2be7ece0-87b5-4298-a68c-11408551e25b@71g2000hse.googlegroups.com> Message-ID: <47BB4E6E.8090705@fmed.uba.ar> castironpi at gmail.com wrote: >Standardization allows RCA cables, bumpers, and 115V plugs. The Bill >of Rights allows Huckleberry Finn. What is the analogue of the Bill >of Rights for programmers and users, whether of programming languages >or latter-generation software? > > I want that drogues, man From tjreedy at udel.edu Fri Feb 29 17:26:39 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 29 Feb 2008 17:26:39 -0500 Subject: convert string number to real number - ValueError: invalid literal for int() with base 10: '"2"' References: <3ca86e1d-a32f-48f2-bc9a-6cb792c0c631@z17g2000hsg.googlegroups.com> Message-ID: "davidj411" wrote in message news:3ca86e1d-a32f-48f2-bc9a-6cb792c0c631 at z17g2000hsg.googlegroups.com... |i am parsing a cell phone bill to get a list of all numbers and the | total talktime spend on each number. | | i already have a unique list of the phone numbers. | now i must go through the list of numbers and add up the totals for | each number. | here is the function i wrote to get one number at a time's total | talktime. | | def getsinglenumbertalktime(number,talktime): | for line in file[0:-2]: ... | | talktime = talktime + li[5] | return talktime It would appear that you are calling this function and rescanning scanning file for each number. It would be more efficient to scan the file once, for each line parsing out the number and minutes and incrementing the minutes for that number. Also, if you had printed repr(li[5]) and len(li[5]) instead of or in addition to just li[5] (which prints str(li[5]), >>> a='"2"' >>> print a, repr(a), len(a) "2" '"2"' 3 you might have seen for yourself the problem that the string contains quote marks and not just digits. Repr and len are useful debugging aids. tjr From rcdailey at gmail.com Thu Feb 7 16:04:06 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Thu, 7 Feb 2008 15:04:06 -0600 Subject: embedding python Message-ID: <496954360802071304v3c0cff94g9dfaff9e3c4cba91@mail.gmail.com> Hi, I'm attempting to embed python into my game. What I want to do is the following: 1) Embed the interpreter into my game (Py_Initialize(), etc) using the Python C API 2) Execute modules from my game using the python interpreter (Using boost.python's objects and handles) 3) Expose C++ interfaces in my game that can be called from modules executed through the interpreter integrated in my application. Number 3, above, is the one I am not sure how to do. I know how to use Boost.Python to create a DLL exposing functions that can be called from any Python module, but I want to expose C++ functions into python for ONLY modules processed by my game. I want game-related function calls (Like CompleteQuest()) to be available to the Python scripts run through my game. This is sort of how LUA works: You define a set of functions in your application that are callable through scripts run BY the game only. Can anyone help me on #3 above? How would I do this? Can you reference me to documentation either in the boost library or python? -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Wed Feb 20 05:42:00 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 20 Feb 2008 10:42:00 GMT Subject: What's "the standard" for code docs? References: <47b69581$0$36393$742ec2ed@news.sonic.net> <96fc10f7-06fd-4e77-b38c-ec63e9b19341@s12g2000prg.googlegroups.com> <3878093e-e723-47f9-a7e3-fcfca012fa74@n77g2000hse.googlegroups.com> <26ae371c-0769-4434-9cd3-704ff8c81701@p43g2000hsc.googlegroups.com> Message-ID: <622efoF212v06U1@mid.uni-berlin.de> On Tue, 19 Feb 2008 16:37:23 -0800, Preston Landers wrote: > On Feb 19, 4:31 pm, castiro... at gmail.com wrote: > > But after reading some of your other recent posts on other topics, I'm > not confident that it was intended to make sense at all. Have a little bit patience, the bot is still in its early learning phase. ;-) Ciao, Marc 'BlackJack' Rintsch From george.sakkis at gmail.com Tue Feb 12 21:15:42 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 12 Feb 2008 18:15:42 -0800 (PST) Subject: ways to declare empty set variable References: <56a14$47b1a306$839b8704$9583@news2.tudelft.nl> <5099c$47b1a77b$839b8704$11089@news2.tudelft.nl> <7xhcgd7tof.fsf@ruckus.brouhaha.com> <719e7c26-7d52-4b78-875c-fc7d5ca32f4e@s19g2000prg.googlegroups.com> <874pcdzsho.fsf@benfinney.id.au> <87zlu5yb9h.fsf@benfinney.id.au> Message-ID: <6dd61cff-f27e-42e7-9802-7220e063fa07@y5g2000hsf.googlegroups.com> On Feb 12, 7:02 pm, Ben Finney wrote: > Steve Holden writes: > > Ben Finney wrote: > > [...] > > > > Note that '()' is syntactically null. Parentheses don't declare a > > > tuple literal, commas do. Parentheses are for grouping within > > > expressions, not specifying type. > > > Tell that to the interpreter: > > > >>> type(()) > > > > >>> tuple() is () > > True > > Well, knock me down with a kipper. > > That makes it even more a violation of principle-of-least-astonishment > that the '(foo)' form doesn't give a one-element tuple literal. The reason being, of course, that in this case '(1+2) * 3' would give a result several orders of magnitude more astonishing, so it's well worth the slight inconvenience of one-element tuples. George From python.list at tim.thechases.com Tue Feb 26 11:45:12 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 26 Feb 2008 10:45:12 -0600 Subject: Break lines? In-Reply-To: References: Message-ID: <47C44218.5020807@tim.thechases.com> > Ok thanks! Btw why double quotes " instead of single ' ? Either one will do...there's not much difference. I try to use double-quotes most of the time, just so when I include an apostrophe in-line (which I do more often than I include a double-quote in-line), I don't have to think. string1a = "John's dog" string1b = 'John\'s dog' string2a = "She said \"hello\"" string2b = 'She said "hello"' string3a = 'She said "John\'s nice" in a letter' string3b = "She said \"John's nice\" in a letter' string3c = """She said "John's nice" in a letter""" string3d = '''She said "John's nice" in a letter''' My usual aim is for clarity, so I tend to go with the versions that have the fewest backslashes in them. -tkc From jorge.vargas at gmail.com Wed Feb 20 09:05:47 2008 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Wed, 20 Feb 2008 08:05:47 -0600 Subject: is this data structure build-in or I'll have to write my own class? In-Reply-To: References: Message-ID: <32822fe60802200605o3d46c0bds2e5ff327a510292a@mail.gmail.com> dict doesn't maintains order. >>> a=[(3,2),(2,2)] >>> dict(a).items() [(2, 2), (3, 2)] >>> a=[(3,2),(2,2)] >>> assert dict(a).items()==a Traceback (most recent call last): File "", line 1, in AssertionError >>> dict(a).items() [(2, 2), (3, 2)] On Feb 20, 2008 7:50 AM, subeen wrote: > I think you should go for 'dictionary' that is a built-in data > structure of Python. > > > regards, > Subeen > http://love-python.blogspot.com/ > > > On Feb 20, 7:32 pm, "Jorge Vargas" wrote: > > 2008/2/20 Jarek Zgoda :> Jorge Vargas napisa?(a): > > > > > > - attribute access (or index) > > > > - maintain the order (for iter and print) > > > > - be mutable. > > > > > These are all attributes of standard Python lists. > > > > probably I confused you with the "or index" part. I want to be able to > > do item.value1 or item['value1'] the list can't do this. > > > > > > in case there isn't one. I was thinking having a base class like Bunch > > > >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308and on > > > > top of that keeping a list of the keys and pop/push to the list when > > > > adding/deleting items. I don't like this idea because I'll have to > > > > keep each key twice. (in the list and in __dict__, is this the only > > > > way of doing it? > > > > > What is your objective? From the description of this recipe I cann't get > > > your use case. > > > > I got an xml object which feed me in data. in a simple format > > > > foo > > bar > > baz > > bal > > > > > > I want to turn this into a datastructure I can manipulate in my > > program for example. > > > > >>> print myItem.property1 > > >>> if myItem.property1[value1] > 0: > > > > print 'ok' > > > > >>> print myItem > > > > {'property1':'value1','property2,'value2'} > > > > > > > > > > > > > -- > > > Jarek Zgoda > > > Skype: jzgoda | GTalk: zg... at jabber.aster.pl | voice: +48228430101 > > > > > > "We read Knuth so you don't have to." (Tim Peters) > > > -- > > >http://mail.python.org/mailman/listinfo/python-list > > -- > http://mail.python.org/mailman/listinfo/python-list > From software at ginstrom.com Sat Feb 23 07:53:56 2008 From: software at ginstrom.com (Ryan Ginstrom) Date: Sat, 23 Feb 2008 21:53:56 +0900 Subject: Article of interest: Python pros/cons for the enterprise In-Reply-To: References: <2f1527a7-2f66-44c7-9665-4d8ff01fa5ab@28g2000hsw.googlegroups.com><47bd4a24$0$25225$426a74cc@news.free.fr><036e93e6-5840-4a3c-8642-67a0a9ec44f2@i7g2000prf.googlegroups.com><784ec210-f389-4a15-b458-961100de9103@v3g2000hsc.googlegroups.com><0ca5ddf3-98b6-4f58-93bf-7d0f6576469e@e60g2000hsh.googlegroups.com><691de0bd-a9cc-4e24-8175-89c0863eac9f@u69g2000hse.googlegroups.com> Message-ID: <062c01c8761b$270cbd40$0203a8c0@MOUSE> > On Behalf Of Jeff Schwab > When I see this silliness again and again, it really breaks > my heart If you allow your heart to be broken by others' opinions, you're setting yourself up for a lot of disappointment IMHO. I personally used C++ for about 90% of my code for 10 years. During that time, I was chugging the C++ Kool-Aid so hard I almost peed myself. I still think that C++ is a beautiful language, but I have also come to think that starting a program with C++ is a premature optimization. I think that very few Python programmers today started with Python. Most of them came to Python for a reason. Regards, Ryan Ginstrom From ptmcg at austin.rr.com Fri Feb 22 12:27:56 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 22 Feb 2008 09:27:56 -0800 (PST) Subject: Simple - looking for a way to do an element exists check.. References: Message-ID: On Feb 22, 11:20?am, rh0dium wrote: > > found = False > for item in a: > ? if item[0] == element[0] > ? ? found = True > ? ? break > if not found: > ? a.append(element) > > But this is just ugly - Is there a simpler way to interate over all > items in a without using a found flag? > > Thanks for item in a: if item[0] == element[0] break else: # only called if we never 'break' out of the for loop a.append(element) But what about a dict? adict = dict((elem[0],elem) for elem in a) if item[0] not in adict: adict[item[0]] = item # need the final list? a = adict.values() No list searching, and will scale well if a gets real long. -- Paul From ninja.krmenadl at fer.hr Fri Feb 22 16:13:01 2008 From: ninja.krmenadl at fer.hr (Boris Ozegovic) Date: Fri, 22 Feb 2008 22:13:01 +0100 Subject: Pydev, Eclipse References: Message-ID: Preston Landers wrote: > Shift-Tab does it for me. It can also dedent whole blocks if you have > them selected. Excellent. Thank you. From gherron at islandtraining.com Mon Feb 18 18:53:08 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 18 Feb 2008 15:53:08 -0800 Subject: Understanding While Loop Execution In-Reply-To: References: Message-ID: <47BA1A64.4070201@islandtraining.com> Brad wrote: > Hi folks, > > I'm still fairly new to programming in python and programming in > general. A friend of mine is in a CompSci 101 course and was working > on a slider game when he encountered a problem. We eventually figured > out what the problem was and built a test case to help solve it, but I > can't for the life of me figure out the why behind it. I tried > googling it and searching the list but didn't find anything that > really explained it. I'm sure it's probably just both of us > misunderstanding what the "while" statement does. So I hoped to ask > for some clarification here. So here is what we worked out was going > on with his code. > > from random import shuffle > > mylist=[2,1,3] > baselist=[1,2,3] > newlist=[] > count=0 > while mylist!=baselist: > count+=1 > shuffle(mylist) > newlist.append(mylist) > print count, mylist, newlist > > Output: > > 1 [3, 1, 2] [[3, 1, 2]] > 2 [1, 2, 3] [[1, 2, 3], [1, 2, 3]] > > > What he wanted was a list of lists to use later as a replay. What we > expected newlist.append(mylist) to do was to save a copy of mylist > into the collection for each iteration of the while statement. > However, what struck us as odd is that for each time the while loop > executes it changes all the lists in the list. What I found even > exasperating was if I created yet another list. > > from random import shuffle > > mylist=[2,1,3] > baselist=[1,2,3] > newlist=[] > saved_shufs=[] > count=0 > > while mylist!=baselist: > count+=1 > shuffle(mylist) > newlist.append(mylist) > saved_shufs.append(newlist[0]) > print count, mylist, newlist[0], saved_shufs > > Output: > > 1 [1, 3, 2] [1, 3, 2] [[1, 3, 2]] > 2 [3, 2, 1] [3, 2, 1] [[3, 2, 1], [3, 2, 1]] > 3 [1, 2, 3] [1, 2, 3] [[1, 2, 3], [1, 2, 3], [1, 2, 3]] > > > newlist[0] printed out correctly but when appending it into > saved_shufs it still overwrote everything. > > Eventually, after plinking about I remembered that tuples were > immutable and wound up creating a variable like > tuple_of_mylist=tuple(mylist) then appending that into newlist. That > kept the list of tuples fine. I'm still wondering though what I'm not > grasping about "while" that made it do that to the lists? Or is it not > even while, is it something else I'm not getting? > > Thanks in advance, > B > First of all, it's got nothing to do with the while loop. The Python feature that's biting you here is the fact that lists are not *copied* when you work with them. So in the following code, the list named full does not have 3 copies of sub in it, but rather it has 3 *references* to the single list named sub. Any changes to the list named sub will be reflected anywhere that list is referred to. >>> sub = [1,2,3] >>> full = [sub,sub,sub] >>> full [[1, 2, 3], [1, 2, 3], [1, 2, 3]] >>> sub[0] = 123 >>> full [[123, 2, 3], [123, 2, 3], [123, 2, 3]] So in you code, the single list mylist is shuffled each time, and newlist keeps growing my more references to it. If you want a *copy* of the list, you have to explicitly ask for one. The easiest way to do that is mylist[:]. (This is a shorthand for copying out any sublist of mylist via the syntax mylist[a:b], with a and b defaulting to whole list.) Gary Herron From inq1ltd at inqvista.com Wed Feb 6 10:32:23 2008 From: inq1ltd at inqvista.com (jim-on-linux) Date: Wed, 06 Feb 2008 10:32:23 -0500 Subject: Tkinter fonts setting In-Reply-To: <47A8C59E.4070100@gmail.com> References: <47A8C59E.4070100@gmail.com> Message-ID: <200802061032.23352.inq1ltd@inqvista.com> On Tuesday 05 February 2008 15:22, Unnamed One wrote: > First question - is it possible to set > font to default OS font for window text? > It would be preferable, while on my > Windows XP system Tkinter sets small > Helvetica-style font by default. > > Secondly, can I set font globally (or > specify "default" font for widgets)? In > fact, all I want is to get default OS font > unless (rarely) I need to specify another. > > Thanks Go to: http://www.pythonware.com/library/tkinter/introduction/ Read chapter 6, Widget Styling, there is a section on Fonts which has a sub-section on System Fonts. jim-on-linux http://www.inqvista.com From steve at holdenweb.com Wed Feb 6 09:18:22 2008 From: steve at holdenweb.com (Steve Holden) Date: Wed, 06 Feb 2008 09:18:22 -0500 Subject: Why chdir command doesn't work with client.get_transport() ? In-Reply-To: References: <15297822.post@talk.nabble.com> Message-ID: <47A9C1AE.5070708@holdenweb.com> I try not to top-post in this group, but the strange formatting of the message makes this advisable, as I am sure many people won't even persist in reading down as far as the "content". Can I make a wild-assed guess that you are a Lotus Notes user reading python-list? Please try and find a way of not barfing these awful headers out with your post (perhaps you could use a newsgroup reader and access the gmane servers?). It really does make it difficult to focus on what you say when there are twenty-odd lines of badly-formatted heading information at the start of each message. regards Steve Matthew_WARREN at bnpparibas.com wrote: > > Internet > charles_hans at yahoo.com > To > python-list > Sent by: cc > python-list-bounces+matthew.warren=uk.bnpparibas.com@ > python.org Subject > Re: Why chdir command doesn't work with > 05/02/2008 19:39 client.get_transport() ? > > > > > > > > > > > > > > > > >> Thank you, Matt, for your valuable advice! I did try using ';' to issue > three >> commands at once and it works! >> >> However, I have more problems with issuing ClearCase commands, which is > what >> I am really doing. >> >> Under telnet, I could issue commands one by one, just as typing at the >> command prompt. Now I tried to use ';' manually typing two commands at > once >> on my Solaris command line, such as >> >> ct setview viewName; cd dir_in_clearcase >> >> (ct = cleartool) The second command will not be executed, since the > command >> prompt changes after the first command. --- I think that it was because >> there was a long delay after the first command. (any way out?) > > I'm not familiar with cleartool - could it be that the first command you > are using is invoking an application that is not returning to the command > line?, for example, if you were telnetted in and doing the same would you > literally type > > $>ct setview viewName > $>cd /some/where > > or does the session look more like > > $>ct setview viewName > _new_ct_prompt> exit > $>cd /some/where > > If that is the case, it mightbe possible to direct ct to get it's input > from a file > > ct setview viewName < exitfile; cd /some/where > > and exitfile has the word 'exit' in it. > > just an idea though. may not work. > > >> When I used exec_command() to do this in Python, even the first command > was >> not recognized (error: bad phone number. I used 'man ct' and found that > ct >> dials a phone number). Even if 'ct' was recognized, the second command > would >> not be executed. And it is useless to do it in the next exec_command() >> function. (Without the first command, one can not cd into a directory in >> ClearCase.) > > I'm a bit confused here. - Do you have an application called 'ct' (from > previous paragraph, it appears you do. But if you are issuing 'ct' via > python and getting 'bad phone number'??) Can you explain the bigger > picture a bit more, and what ClearCase is? > > Why do you say 'Even if ct was recognized, the second command would not be > executed' - if ct was recognised and returns to the command line prompt I > would fully expect the second command to execute. > > >> Do you think that paramiko can replace telnet in my application? Thanks. > > I think it would be taking it a bit far if you are just trying to automate > something unless you really have to run on a remote machine. Then either > telnet or paramiko should work. You could also maybe look at using python > to invoke rsh/rexec processes if telnet was suitable in the first place. > > Matt > > > > > > > > This message and any attachments (the "message") is > intended solely for the addressees and is confidential. > If you receive this message in error, please delete it and > immediately notify the sender. Any use not in accord with > its purpose, any dissemination or disclosure, either whole > or partial, is prohibited except formal approval. The internet > can not guarantee the integrity of this message. > BNP PARIBAS (and its subsidiaries) shall (will) not > therefore be liable for the message if modified. > Do not print this message unless it is necessary, > consider the environment. > > --------------------------------------------- > > Ce message et toutes les pieces jointes (ci-apres le > "message") sont etablis a l'intention exclusive de ses > destinataires et sont confidentiels. Si vous recevez ce > message par erreur, merci de le detruire et d'en avertir > immediatement l'expediteur. Toute utilisation de ce > message non conforme a sa destination, toute diffusion > ou toute publication, totale ou partielle, est interdite, sauf > autorisation expresse. L'internet ne permettant pas > d'assurer l'integrite de ce message, BNP PARIBAS (et ses > filiales) decline(nt) toute responsabilite au titre de ce > message, dans l'hypothese ou il aurait ete modifie. > N'imprimez ce message que si necessaire, > pensez a l'environnement. -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From nicola.musatti at gmail.com Fri Feb 22 06:01:53 2008 From: nicola.musatti at gmail.com (Nicola Musatti) Date: Fri, 22 Feb 2008 03:01:53 -0800 (PST) Subject: Article of interest: Python pros/cons for the enterprise References: <2f1527a7-2f66-44c7-9665-4d8ff01fa5ab@28g2000hsw.googlegroups.com><47bd4a24$0$25225$426a74cc@news.free.fr> <036e93e6-5840-4a3c-8642-67a0a9ec44f2@i7g2000prf.googlegroups.com> <784ec210-f389-4a15-b458-961100de9103@v3g2000hsc.googlegroups.com> <5MSdncqVGdEXiSPanZ2dnUVZ_vPinZ2d@comcast.com> Message-ID: On Feb 22, 1:17 am, Jeff Schwab wrote: [...] > If you've already got a generic, language-supported way to manage > resources (like RAII with deterministic destruction), then why bother > with garbage collection? I'm not trying to knock it; it was a big step > up from C-style "who forgot to delete a pointer" games. It just seems > to me like a solution to something that's no longer a problem, at least > in well-written C++ code. I'll take destructors over GC any day. The real point about garbage collection is that it's about the only way to ensure that an object of one type is never taken to be of another type, e.g. by keeping around pointers to the object that occupied its memory before it was reallocated. I believe that this degree of type safety is worth having, which is why I favour the addition of optional GC to C++. Cheers, Nicola Musatti From t at nomail.com Sat Feb 16 10:37:16 2008 From: t at nomail.com (T_T) Date: 16 Feb 2008 15:37:16 GMT Subject: simple python script to zip files Message-ID: <47b7032c$0$54085$dbd4b001@news.wanadoo.nl> Hi, I'm just starting to learn some Python basics and are not familiar with file handling. Looking for a python scrip that zips files. So aaa.xx bbb.yy ccc.xx should be zipped to aaa.zip bbb.zip ccc.zip I haven't been able to type more than 'import gzip'.. Just a script I need for practical use (zip didn't do the job) and not for educational purposes. From jeff at schwabcenter.com Sat Feb 9 16:37:23 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Sat, 09 Feb 2008 13:37:23 -0800 Subject: sort functions in python In-Reply-To: References: <13qq49c705dnc2a@corp.supernews.com> Message-ID: Carl Banks wrote: > On Feb 8, 10:09 pm, Jeff Schwab wrote: >> If you expect your data to be pretty nearly sorted >> already, but you just want to make sure (e.g. because a small number of >> elements may have been inserted or removed since the last sort), >> bubble-sort is a good choice. > > But if you're at that stage you probably were doing something wrong in > the first place. How do you figure? You don't always have control over the insertions/replacements, or where they happen. As a silly example, assume you have a sorted list of children, by height. Maybe you check your list once per school semester. The new sort order for any given semester will likely be very close to the previous order; however, a few swaps may be in order, according to the different speeds at which children have grown. > For a list of any decent size a few insertions using a bisection > algorithm will take fewer comparisons than a single bubblesort pass. Do you mean that if newly inserted data are kept separate from the already-sorted list, then they can be merged into the list in O(log N) time? From devnew at gmail.com Thu Feb 21 02:41:22 2008 From: devnew at gmail.com (devnew at gmail.com) Date: Wed, 20 Feb 2008 23:41:22 -0800 (PST) Subject: using PIL for PCA analysis Message-ID: <8d9c20ee-f277-4c53-9e67-028f34958192@s37g2000prg.googlegroups.com> hi guys i am trying out PCA analysis using python.I have a set of jpeg(rgbcolor) images whose pixel data i need to extract and make a matrix .( rows =num of images and cols=num of pixels) For this i need to represent an image as an array. i was able to do this using java's BufferedImage as below int[] rgbdata = new int[width * height]; image.getRGB(0,0,width,height,rgbdata,0,width); doubles = new double[rgbdata.length]; int i; for ( i = 0; i < bytes.length; i++) { doubles[i] = (double)(rgbdata[i]); } this doubles[] now represent a single image's pixels then i can get a matrix of say 4 images ..(each of 4X3 size) images[][] rows=4,cols=12 [ [-4413029.0, -1.0463919E7,... -5201255.0] [-5399916.0, -9411231.0, ... -6583163.0] [-3886937.0, -1.0202292E7,... -6648444.0] [-5597295.0, -7901339.0,... -5989995.0] ] i can normalise the above matrix to zeromean and then find covariance matrix by images * transpose(images) my problem is how i can use PIL to do the same thing..if i extract imagedata using im.getdata() i will get [ [(188, 169, 155), (96, 85, 81),.. (176, 162, 153)] [(173, 154, 148), (112, 101, 97),.. (155, 140, 133)] [(196, 176, 167), (100, 83, 76), ... (154, 141, 132)] [(170, 151, 145), (135, 111, 101), ... (164, 153, 149)] ] i donot know how to find covariance matrix from such a matrix..it would'v been ideal if they were single values instead of tuples..i can't use greyscale images since the unput images are all rgb jpeg can someone suggest a solution? thanks dn From thinker at branda.to Mon Feb 25 07:50:17 2008 From: thinker at branda.to (Thinker) Date: Mon, 25 Feb 2008 20:50:17 +0800 Subject: [Newbie] Is there any method to urlretrieve to a file the html source from a url with "Transfer-encoding": chunked In-Reply-To: <9e6f2b22-4414-40b5-b7e9-07654c6a6b79@i29g2000prf.googlegroups.com> References: <9e6f2b22-4414-40b5-b7e9-07654c6a6b79@i29g2000prf.googlegroups.com> Message-ID: <47C2B989.4090802@branda.to> Aldo Ceccarelli wrote: > Hello All, > I apologize for posting a question on this but I could not find a > complete answer after reading and searching so far:-) > > My problem is that I'd like to store the html source of a certain web > url but when I try via urllib / urllib2 reads or urlretrieve I get > only a part of the contents (ist type is text/html). > > Metainformation associated with the url show that it has a: > > Transfer-Encoding: chunked > > and this seems the reason why I can get only a part of it. > Please show your code, here. urllib doesn't always return full content in one time. I guess it is the problem. From bj_666 at gmx.net Sun Feb 3 16:56:18 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 3 Feb 2008 21:56:18 GMT Subject: Does anyone else use this little idiom? References: <7834edc9-58ec-4d62-a77e-383f72614533@k2g2000hse.googlegroups.com> Message-ID: <60mrk2F1ro06iU3@mid.uni-berlin.de> On Sun, 03 Feb 2008 05:33:16 -0800, Ivan Illarionov wrote: > Plain Python function are very often more powerful than classes: > >>>> def go(count): > ... if not hasattr(go, 'count'): > ... go.count = count > ... if go.count <= 0: > ... del go.count > ... return False > ... go.count -= 1 > ... return True > ... >>>> while go(3): > ... print 'hello' > ... > hello > hello > hello >>>> Please try: while go(3): while go(3): print 'Think about it...' Ciao, Marc 'BlackJack' Rintsch From mr.cerutti at gmail.com Fri Feb 1 15:34:16 2008 From: mr.cerutti at gmail.com (Neil Cerutti) Date: Fri, 1 Feb 2008 15:34:16 -0500 Subject: How to identify which numbers in a list are within each others' range In-Reply-To: <406cdd9f-07be-4967-8a4b-83fb246e3f92@v4g2000hsf.googlegroups.com> References: <6b4ac79b-6267-438d-8b28-aa4bba78a586@i3g2000hsf.googlegroups.com> <1ffed8a2-f00b-4913-802f-b2cc9fa0ab19@i12g2000prf.googlegroups.com> <073ebb96-3572-4aa5-88d6-53e97cc55633@c4g2000hsg.googlegroups.com> <406cdd9f-07be-4967-8a4b-83fb246e3f92@v4g2000hsf.googlegroups.com> Message-ID: <51302a8c0802011234m8f8ad54i23554562992cb071@mail.gmail.com> On Feb 1, 2008 3:16 PM, Arnaud Delobelle wrote: > On Feb 1, 2:44 pm, "Neil Cerutti" wrote: > > Here's another contender, basically the same as yours, but spelled > > without iterators. > > > > def overlaps(eranges): > > """Determine, from a list of numbers and a +/- range of uncertainty, which > > number ranges overlap each other. Return the overlapping range indexes as > > a list of overlapping pairs. > > > > >>> sorted(overlaps(((55, 3), (20, 2), (17, 4), (60, 3)))) > > [(0, 3), (1, 2)] > > """ > > d = [(r[0] - r[1], r[0] + r[1], i) for i, r in enumerate(eranges)] > > d.sort() > > rv = [] > > x = 0 > > while x < len(d): > > minx, maxx, ix = d[x] > > y = x+1 > > while y < len(d): > > miny, maxy, iy = d[y] > > if miny < maxx: > > rv.append((ix, iy) if ix < iy else (iy, ix)) > > else: > > break > > y += 1 > > x += 1 > > return rv > > The total number of iterations is 1+2+...+n = n(n+1)/2 (when n is the > number of intervals) so this has quadratic behaviour regardless of > input. See my other post for a 'detailed' analysis of my solution. But it breaks out of the inner loop as soon as ranges on the right cannot overlap. The loop is O(N) for all input if I define N as "number of overlaps", a pretty reasonable definition--it's madness to expect to report N overlaps with less than N complexity. Unless I'm making a silly mistake. Again. -- Neil Cerutti From jeffober at gmail.com Thu Feb 14 12:27:09 2008 From: jeffober at gmail.com (Jeff) Date: Thu, 14 Feb 2008 09:27:09 -0800 (PST) Subject: How to tell if I'm being run from a shell or a module References: <44e07112-e3f5-4446-8522-24c2476efd4a@e10g2000prf.googlegroups.com> Message-ID: <9207b701-99d8-4b95-b75d-d2276c0de521@i29g2000prf.googlegroups.com> Conventionally, you use: if __name__ == '__main__': # do something as a script From bronger at physik.rwth-aachen.de Thu Feb 14 07:59:01 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Thu, 14 Feb 2008 13:59:01 +0100 Subject: Is there any Generic RSS/ATOM generator in Python? References: <87ve4sc80o.fsf@physik.rwth-aachen.de> Message-ID: <87bq6jd78q.fsf@physik.rwth-aachen.de> Hall?chen! js writes: > Trivial? > More than XML::Atom::Feed? > http://search.cpan.org/~miyagawa/XML-Atom-0.28/lib/XML/Atom/Feed.pm Excerpt from my code: root = ElementTree.Element("feed", xmlns="http://www.w3.org/2005/Atom") ElementTree.SubElement(root, "id").text = self.id ElementTree.SubElement(root, "title").text = self.title ElementTree.SubElement(root, "updated").text = format_time(self.updated) Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From http Sat Feb 2 04:17:34 2008 From: http (Paul Rubin) Date: 02 Feb 2008 01:17:34 -0800 Subject: bags? 2.5.x? References: <7xtzkscnu0.fsf@ruckus.brouhaha.com> Message-ID: <7xfxwbpvip.fsf@ruckus.brouhaha.com> Arnaud Delobelle writes: > * For sets {x, y} union {y, z} = {x, y, z}. The natural way of > extending this to multisets is having the union operator take the > max of the multiplicities of each element, i.e. That certainly doesn't fit the intuition of a bag of objects. I'd think of the union of two bags as the result of dumping the contents of both bags onto the table, i.e. you'd add the two vectors. > * Similarly, for intersection one would take the min of > multiplicities, i.e. This is a reasonable interpretation I guess. > A difference B = A - (A intersection B) I think difference would mean subtraction. From jkugler at bigfoot.com Fri Feb 1 13:34:25 2008 From: jkugler at bigfoot.com (Joshua Kugler) Date: Fri, 01 Feb 2008 09:34:25 -0900 Subject: SimpleXMLRPCServer to fastcgi via WSGI? References: Message-ID: Ivan Voras wrote: > Is there a straightforward way to convert an XML-RPC server application > (written for SimpleXMLRPCServer) to use WSGI so that it can be used as s > fastcgi server? By "straightforward" I mean something simple, without > using some external framework. > > Alternatively, I don't really care about WSGI, so something that makes > it work as fastcgi directly will also be ok. You don't need WSGI to use FastCGI. See http://pypi.python.org/pypi/python-fastcgi It says it includes WSGI server implementations, but that doesn't mean you have to use them. j From malaclypse2 at gmail.com Thu Feb 7 10:40:25 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Thu, 7 Feb 2008 10:40:25 -0500 Subject: socket script from perl -> python In-Reply-To: <0febf060-a950-451c-9b13-6ec155160e96@i29g2000prf.googlegroups.com> References: <0febf060-a950-451c-9b13-6ec155160e96@i29g2000prf.googlegroups.com> Message-ID: <16651e80802070740s3810d19el68d6a93e8eb34ed2@mail.gmail.com> On Feb 7, 2008 9:39 AM, kettle wrote: > f = open('/home/myuname/socket.wav','rb') > audio = "" > for line in f: > audio += line I don't know anything about socket programming in python, but this bit doesn't seem right for working on a binary file. You should just read all of the data into audio in one go, like this: f = open('/home/myuname/socket.wav','rb') audio = f.read() There's no need to iterate over the lines in the file, since it's quite likely that there really aren't any 'lines' in a binary file. -- Jerry From spe.stani.be at gmail.com Mon Feb 18 09:58:42 2008 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: Mon, 18 Feb 2008 06:58:42 -0800 (PST) Subject: ANN: Phatch = PHoto bATCH processor and renamer based on PIL Message-ID: <15f9eaeb-8d02-4090-922e-97a65c20fe51@e23g2000prf.googlegroups.com> I'm pleased to announce the release of Phatch which is a powerful batch processor and renamer. Phatch exposes a big part of the Python Imaging Library through an user friendly GUI. (It is using python-pyexiv2 to offer more extensive EXIF and IPTC support.) Phatch is not targeted at manipulating individual pictures (such as with Gimp), but repeating the same actions on hundreds or thousands of images. If you know PIL and have some nice recipes laying around, it is very easy to write plugins as Phatch generates the corresponding GUI automagically just like in Django. Any existings PIL scripts can be added very easily. Let me know if you want to contribute or have any questions. Homepage: http://photobatch.stani.be (free download link below) Tutorials: http://photobatch.wikidot.com/tutorials Translations: https://translations.launchpad.net/phatch/trunk/+pots/phatch License: GPLv3 Screenshot: http://photobatch.wikidot.com/local--files/start/Screenshot-Phatch3d.jpg (the perspective and reflection is produced by Phatch itself) Phatch has many features, like: - EXIF information inspector with thumbnail - limit jpeg file size when saving - tons of actions organized by tags (including perspective, round corners, shadow, reflection, ...) - console version (Phatch can now run without a gui on servers) - batch rename and copy files based on exif metadata - data stamping (http://photobatch.wikidot.com) - online documentation wiki (http://photobatch.wikidot.com) Linux only features: - desktop or panel droplets on which images or folders can be dropped (will be ported to Windows & Mac) - Nautilus and desktop integration (with its own mime type and nautilus extension) - manpage with examples With python-pyexiv2 the following featues are added: - embedding the original EXIF and IPTC tags in the image All actions mostly have a separate pil function in their source code, so they could be read as a recipe book for PIL: * Auto Contrast - Maximize image contrast * Background - Put colour under transparent image * Border - Crop or add border to all sides * Brightness - Adjust brightness from black to white * Canvas - Crop the image or enlarge canvas without resizing the image * Colorize - Colorize grayscale image * Common - Copies the most common pixel value * Contrast - Adjust from grey to black & white * Convert Mode - Convert the color mode of an image (grayscale, RGB, RGBA or CMYK) * Copy - Copy image file * Effect - Blur, Sharpen, Emboss, Smooth, ... * Equalize - Equalize the image histogram * Fit - Downsize and crop image with fixed ratio * Grayscale - Fade all colours to gray * Invert - Invert the colors of the image (negative) * Maximum - Copies the maximum pixel value * Mask - Apply a transparency mask * Median - Copies the median pixel value * Minimum - Copies the minimum pixel value * Offset - Offset by distance and wrap around * Posterize - Reduce the number of bits of colour channel * Perspective - Shear 2d or 3d * Rank - Copies the rank'th pixel value * Reflect - Drops a reflection * Rename - Rename image file * Rotate - Rotate with random angle * Round - Round or crossed corners with variable radius and corners * Saturation - Adjust saturation from grayscale to high * Save - Save an image with variable compression in different types * Scale - Scale an image with different resample filters. * Shadow - Drop a blurred shadow under a photo with variable position, blur and color * Solarize - Invert all pixel values above threshold * Text - Write text at a given position * Transpose - Flip or rotate an image by 90 degrees * Watermark - Apply a watermark image with variable placement (offset, scaling, tiling) and opacity I develop Phatch on Ubuntu/Linux, but I have tested and polished it regularly on Windows and Mac Os X. (Only the droplet functionality needs to be ported.) Phatch is submitted to Debian unstable and Ubuntu Hardy. Packagers for other platforms are welcome. Requirements: - PIL 1.1.5 or higher - wxPython 2.6 or higher - pyexiv2 (optional) - python nautilus bindings (optional) Best regards, Stani -- http://pythonide.stani.be From grante at visi.com Sun Feb 10 16:57:39 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 10 Feb 2008 21:57:39 -0000 Subject: Turn off ZeroDivisionError? References: <45349320-fe77-4581-ba88-064cc81667a3@e6g2000prf.googlegroups.com> Message-ID: <13qusqjp35o1maf@corp.supernews.com> On 2008-02-10, Jeff Schwab wrote: > Neal Becker wrote: >> endangeredmassa at gmail.com wrote: >> >>> Would a wrapper function be out of the question here? >>> >>> def MyDivision(num, denom): >>> if denom==0: >>> return "NaN" >>> else >>> return num / denom >> >> I bought a processor that has hardware to implement this. Why do I want >> software to waste time on it? > > Will the amount of time wasted by the software exceed the amount of time > required to implement Python-level access to the hardware feature? The "time required to implement Python-level access to the hardware features" is simply the time required to delete the lines of code that raise an exception when demon is 0.0 > At any rate, the work-around should at least let you work on > the rest of the application, while a more efficient > implementation can be developed. A more efficient implementation? Just delete the code that raises the exception and the HW will do the right thing. -- Grant Edwards grante Yow! Do you need at any MOUTH-TO-MOUTH visi.com resuscitation? From dotancohen at gmail.com Wed Feb 13 01:59:14 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Wed, 13 Feb 2008 08:59:14 +0200 Subject: OT: Speed of light [was Re: Why not a Python compiler?] In-Reply-To: <20080213064100.GN28991@nexus.in-nomine.org> References: <6f-dnfwZwvz6Ui3anZ2dnUVZ_oOnnZ2d@speakeasy.net> <13r2p6aivk1no9a@corp.supernews.com> <880dece00802121311n77f73515ve7db8a931825d958@mail.gmail.com> <20080213064100.GN28991@nexus.in-nomine.org> Message-ID: <880dece00802122259s760610ffxdb84b15b6cd5ce94@mail.gmail.com> On 13/02/2008, Jeroen Ruigrok van der Werven wrote: > -On [20080212 22:15], Dotan Cohen (dotancohen at gmail.com) wrote: > >Note that Google will give a calculator result for "1 kilogram in > >pounds", but not for "1 kilogram in inches". I wonder why not? After > >all, both are conversions of incompatible measurements, ie, they > >measure different things. > > > Eh? Last I checked both pound and kilogram are units of mass, so where is > the incompatibility? > Pound is a unit of force. That's why people like to say that you will weigh 1/6th on the moon. If here you are 75 kilo, 165 pound, on the moon you should be 75 kilo, 28 pound. Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From benhoyt at gmail.com Thu Feb 21 14:37:15 2008 From: benhoyt at gmail.com (benhoyt) Date: Thu, 21 Feb 2008 11:37:15 -0800 (PST) Subject: Double underscores -- ugly? References: Message-ID: <5c4fb822-56b7-4ec9-80a2-efb2bbf2dc07@d21g2000prf.googlegroups.com> > Has anyone thought about alternatives? Is there a previous discussion > on this I can look up? Okay, I just emailed the BDFL and asked if he could tell me the origin of the double underscore syntax for __special__ methods, and what he said I'm pretty sure he won't mind me posting here: > [Guido van Rossum said:] > The specific naming convention was borrowed from the C standard, which > reserves names like __FILE__ and __LINE__. The reason for needing a > convention for "system-assigned" names was that I didn't want users to > be surprised by the system giving a special meaning to methods or > variables they had defined without intending that special meaning, > while at the same time not wanting to introduce a physically separate > namespace (e.g. a separate dict) for system names. I have no regrets. After that and this thread, I'm pretty good with it, I guess. :-) Cheers, Ben. From tjreedy at udel.edu Wed Feb 27 01:59:48 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 27 Feb 2008 01:59:48 -0500 Subject: Unknown locale error for Malayalam language in Python References: <8675c4a8-7a56-4c71-aa97-23842d9c6bc4@u10g2000prn.googlegroups.com> Message-ID: "maxinbjohn" wrote in message news:8675c4a8-7a56-4c71-aa97-23842d9c6bc4 at u10g2000prn.googlegroups.com... | Dear friends, | | I am a Python programmer from Kerala, India. When I tried to run a | simple python program which uses the Malayalam language (ml), | | import os | import locale | os.environ['LANG']='ml' | print locale.getdefaultlocale() | | | It throws the following error : | | Traceback (most recent call last): | File "test.py", line 4, in ? | print locale.getdefaultlocale() | File "/usr/local/lib/python2.4/locale.py", line 346, in | getdefaultlocale | return _parse_localename(localename) | File "/usr/local/lib/python2.4/locale.py", line 278, in | _parse_localename | raise ValueError, 'unknown locale: %s' % localename | ValueError: unknown locale: ml | | Thanks in advance. If you have a question, you should say what it is. The error message seems clear to me. The known locales depend on the OS and C compiler. tjr From lasses_weil at klapptsowieso.net Tue Feb 5 18:04:35 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Wed, 06 Feb 2008 00:04:35 +0100 Subject: Project naming suggestions? In-Reply-To: References: Message-ID: <47a8ebb3$0$25368$9b4e6d93@newsspool4.arcor-online.net> Neil Cerutti wrote: > On Feb 3, 2008 1:17 PM, wrote: >> I'm considering writing a little interpreter for a python-like >> language and I'm looking for name suggestions. :-) >> >> Basically, I don't want to change a whole lot about Python. In fact, >> I see myself starting with the compiler module from Python 2.5 and >> building from there. >> >> This language would be more or less "Python modulo a few >> (incompatible) changes, but it'd be recognizable by Python >> programmers. I'm talking about stuff like "allowing the character '?' >> in identifier names," and "a better way to express 'for dummy in >> xrange (n):' when the index isn't needed." I'd also like to >> implement most of the planned Python 3000 changes. >> >> Any suggestions? I'm thinking "Ophidian," for the snake connection, >> or, possibly, "Circus," from "Monty Python's Flying Circus." > > Given your stated goals, I like "Phyton." > Hehe :) /W From mentaltruckdriver at gmail.com Fri Feb 29 20:06:51 2008 From: mentaltruckdriver at gmail.com (mentaltruckdriver at gmail.com) Date: Fri, 29 Feb 2008 17:06:51 -0800 (PST) Subject: (Newbie) Help with sockets. References: <146eb331-a79a-4ac7-ba29-a9935643b20f@d4g2000prg.googlegroups.com> <13sf23elprkhg6f@corp.supernews.com> <16d357be-bfb6-4e49-92e5-2b474e0042b6@e6g2000prf.googlegroups.com> <13sg6ejbboqlu26@corp.supernews.com> Message-ID: <083e4a95-5e28-4fc2-b2a0-0d7b6eaf6e42@u72g2000hsf.googlegroups.com> On Feb 29, 9:42?am, Grant Edwards wrote: > On 2008-02-29, mentaltruckdri... at gmail.com wrote: > > >> You claim to be writing a telnet server, yet I don't see any > >> code that actually implements the telnet protocol. Different > >> telnet clients default to different modes, so if you want them > >> in a certain mode, you have to put them in the desired mode by > >> implementing the telnet feature negotiation protocol. > > > OP here - sorry for the confusion, it's just a listener program that > > people connect to via telnet. > > That's what a telnet server _is_: something that people connect > to via telnet. > > > I'll take a look at the Twisted engine and see if that helps at all. > > Make sure it has telnet protocol support, or you're going to > end up with similar problem. > > -- > Grant Edwards ? ? ? ? ? ? ? ? ? grante ? ? ? ? ? ? Yow! Four thousand > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? at ? ? ? ? ? ? ? different MAGNATES, MOGULS > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?visi.com ? ? ? ? ? ?& NABOBS are romping in my > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?gothic solarium!! Thanks for all the responses, the Twisted engine was exactly what I needed. Thanks for all your help guys! From starsareblueandfaraway at gmail.com Fri Feb 22 08:14:51 2008 From: starsareblueandfaraway at gmail.com (Roy H. Han) Date: Fri, 22 Feb 2008 08:14:51 -0500 Subject: OT: Ideas for a first course using Python In-Reply-To: References: Message-ID: <6a5569ec0802220514n4b3da323x31f28e5e45166300@mail.gmail.com> Ishwar, You might want to focus on applications of Python. For example, you might have a few lectures on web development using mod_python, scientific computing using numpy, windows scripting using win32com and GUI development using wxPython and wxGlade. Roy On Fri, Feb 22, 2008 at 7:50 AM, mikhail.savitsky at gmail.com < mikhail.savitsky at gmail.com> wrote: > On Feb 22, 2:20 am, Mike Driscoll wrote: > > On Feb 21, 4:48 pm, ishwar.rat... at gmail.com wrote: > > > > > > > > > Sorry to butt in but I am shopping for some ideas. > > > > > I am interested in putting together a programming course for non- > > > programmers (outside the computer science domain) based on Pyhton. I > > > envision the course > > > similar to ones that used old-Basic interpreter. > > > > > Any one out there has such a course (already designed) or has some > > > experience > > > of such a course? > > > > > What could be a list of topics to be addressed in such a course > > > (domain), other > > > than the language syntax? > > > > > -ishwar > > > > This guy's been doing it for a while now as a college course: > http://mcsp.wartburg.edu/zelle/python/python-first.html > > > > Mike > > You might want to take a look at > > http://swc.scipy.org/lec/unified.html > > It is superb and fits nicely your description. > > HTH > > Mikhail > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nicola.musatti at gmail.com Tue Feb 26 07:55:13 2008 From: nicola.musatti at gmail.com (Nicola Musatti) Date: Tue, 26 Feb 2008 04:55:13 -0800 (PST) Subject: Article of interest: Python pros/cons for the enterprise References: <2f1527a7-2f66-44c7-9665-4d8ff01fa5ab@28g2000hsw.googlegroups.com><47bd4a24$0$25225$426a74cc@news.free.fr> <036e93e6-5840-4a3c-8642-67a0a9ec44f2@i7g2000prf.googlegroups.com> <784ec210-f389-4a15-b458-961100de9103@v3g2000hsc.googlegroups.com> <5d351937-e1bc-44ab-810d-11f226793b2e@b29g2000hsa.googlegroups.com> <345444fd-4c1c-460d-a402-5702b42f810e@c33g2000hsd.googlegroups.com> Message-ID: On Feb 26, 12:58 pm, Paul Boddie wrote: > On 25 Feb, 19:44, Nicola Musatti wrote: > > > > > Witness the kind of > > libraries/framework that used to and still come with some commercial C+ > > + implementation, and even some free/open source ones; Boost, ACE and > > wxWidgets are the first that come to mind. > > Oh, that's another good reason for C++'s decline: the fragmentation of > the development community through a plethora of proprietary products, > each one with its advocates and a relatively small common ground > (admittedly growing over the years thanks to Free Software and > standards) between them all. When Java came along, even though the > best GUI offering was AWT, it was better than nothing and it was one > of the batteries included. Although Sun's Java was also proprietary, > it was easier for people to obtain and redistribute, often without per- > seat or per-unit licensing costs. C++ was born and acquired its popularity in a period when freely available software wasn't as common as it is today and corporation didn't see any kind of advantage in investing in it. By the way, funny you should mention AWT, given how it was soon superceded by Swing, which in turn competes against SWT. And given the state of the Python web framekork scene if I were you I'd start looking for another language ;-) Cheers, Nicola Musatti From regallpeople at gmail.com Mon Feb 18 14:06:02 2008 From: regallpeople at gmail.com (dawa-dawa) Date: Mon, 18 Feb 2008 11:06:02 -0800 (PST) Subject: Who is this person?? This is Mohammad Message-ID: <28bb152c-457e-4d92-8934-b2e784ef5ead@s19g2000prg.googlegroups.com> Who is this person?? This is Mohammad Who is this person?? This is Mohammad http://mohammad.islamway.com//?lang=eng From larry.bates at websafe.com Wed Feb 20 09:09:17 2008 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 20 Feb 2008 08:09:17 -0600 Subject: Python seems to be ignoring my except clause... In-Reply-To: <7c1ab99b-844d-43d4-8c54-8a07d223d37c@u72g2000hsf.googlegroups.com> References: <7c1ab99b-844d-43d4-8c54-8a07d223d37c@u72g2000hsf.googlegroups.com> Message-ID: Adam W. wrote: > I am trying to handle a Unicode error but its acting like the except > clause is not even there. Here is the offending code: > > def characters(self, string): > if self.initem: > try: > self.data.append(string.encode()) > except: > self.data.append('No habla la Unicode') > > And the exception: > > File "C:\Users\Adam\Desktop\XMLWorkspace.py", line 65, in characters > try: > UnicodeEncodeError: 'ascii' codec can't encode character u'\u2026' in > position 83: ordinal not in range(128) > > Its got to be something really dumb I'm missing, this make no sence. Seems that others have addressed you specific problem so I wanted to take this opportunity to save you from hours of frustration in the future (trust me on this one). It is almost NEVER a good idea to use a blank except: clause in your code. The problem is that it catches ALL exceptions, not just the one you are trying to catch. It is much better to determine the exception you are trying to catch here. Example: try: self.data.append(string.encode()) except UnicodeEncodeError: self.data.append('No habla la Unicode') You can spend a lot of time trying to figure out what is going on when your blank except catches all the exceptions. This lets the other exceptions do what they should do. Hope this helps. Larry Bates From gert.cuykens at gmail.com Sun Feb 24 06:11:26 2008 From: gert.cuykens at gmail.com (gert) Date: Sun, 24 Feb 2008 03:11:26 -0800 (PST) Subject: iter(lambda:f.read(8192),'') Message-ID: what is the difference between iter(lambda:f.read(8192), ') and iter(f.read(8192),'') ? From tjreedy at udel.edu Wed Feb 27 15:48:17 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 27 Feb 2008 15:48:17 -0500 Subject: macro in python References: <910313af0802270254i27ca8a65xab54064bd91f4de@mail.gmail.com> Message-ID: "Guilherme Polo" wrote in message news:ac2200130802270508j4d16fb05n15312adec71f2dcd at mail.gmail.com... | 2008/2/27, bharath venkatesh : | > how to create macro in python for set of instruction that is done | > frequently but too less in number to ignore the overhead of function call You can't in Python. Use an external macro program or cut/repeated paste in an editor. | There is lambda, not exactly a macro. Not at all a macro. Purely an abbreviation for def ... | But every program uses functions why cant yours ? Yes, function call overhead is seldom the major slowdown except possibly in inner loops, where code can be written inline just once. tjr From ggpolo at gmail.com Wed Feb 13 05:26:23 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 13 Feb 2008 08:26:23 -0200 Subject: Python not finding modules In-Reply-To: <463504.69478.qm@web94611.mail.in2.yahoo.com> References: <463504.69478.qm@web94611.mail.in2.yahoo.com> Message-ID: 2008/2/13, Mani Chandra : > Hey! > I installed a few python modules through the freebsd ports, but when I try to import them in the interpreter it says "module xxx not found". This seems to happen for some modules and not for the others. ex:- I installed psyco and parallel python which seem to be found but then scipy, PIL aren't being imported. Below is my $PYTHONPATH > > ['', '/usr/local/lib/python2.5/site-packages/setuptools-0.6c7-py2.5.egg', '/usr/local/lib/python25.zip', '/usr/local/lib/python2.5', '/usr/local/lib/python2.5/plat-freebsd6', '/usr/local/lib/python2.5/lib-tk', '/usr/local/lib/python2.5/lib-dynload', '/usr/local/lib/python2.5/site-packages', '/usr/local/lib/python2.5/site-packages/gtk-2.0', '/usr/local/lib/vtk/python', '/usr/local/lib/python2.5/site-packages'] > > The scipy libs are located at "/usr/local/lib/python2.4/site-packages/scipy" so I manually added this path to the PYTHONPATH but it still doesn't seem to find it. > You need to install python modules for python2.5, you clearly installed for 2.4. > Can someone please help me out here?:) > > ps Also does including a directory in PYTHONPATH include all of it's sub-directories too? > > > > Download prohibited? No problem. CHAT from any browser, without download. Go to http://in.messenger.yahoo.com/webmessengerpromo.php/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From grante at visi.com Thu Feb 28 18:26:04 2008 From: grante at visi.com (Grant Edwards) Date: Thu, 28 Feb 2008 23:26:04 -0000 Subject: How about adding rational fraction to Python? References: <13scs8k1kh9nk81@corp.supernews.com> <13see4t3s23pn59@corp.supernews.com> Message-ID: <13segoctgii63cd@corp.supernews.com> On 2008-02-28, Steven D'Aprano wrote: > But that's not true. The consensus, across the majority of > people (both programmers and non-programmers alike) is that > 1/2 should return 0.5. There's a small minority that argue > for a rational result, and a bigger minority who argue for 0. Yeay! I'm in the bigger minority! > The interesting case is -1/2. According to the argument that > "2 doesn't go into 1", -1/2 should also return 0. But that's > not what Python returns, so it looks like the "int division" > camp is screwed no matter whether Python keeps the status quo > or the other status quo. I do integer division pretty regularly, but apparently never on negative numbers since I wasn't even aware that -1/2 yields -1 (yes, I'm still running 2.4). -- Grant Edwards grante Yow! Awright, which one of at you hid my PENIS ENVY? visi.com From romano.giannetti at gmail.com Mon Feb 25 11:21:58 2008 From: romano.giannetti at gmail.com (romano.giannetti at gmail.com) Date: Mon, 25 Feb 2008 08:21:58 -0800 (PST) Subject: Embedding a literal "\u" in a unicode raw string. References: <47C2BB5C.90608@branda.to> Message-ID: <1503eb5e-0a24-40ca-bc7f-12dcce17e851@72g2000hsu.googlegroups.com> > unicode(r"\uparrow", "utf-8") will break... sigh. > Moreover, I checked with 2to3.py, and it say (similar case): -ok_preamble = unicode(r""" +ok_preamble = str(r""" \usepackage[utf8]{inputenc} \begin{document} A?adidos: """, "utf-8") which AFAIK will give an error for the \u in \usepackage. Hmmm... should I dare ask on the developer list? :-) From wanja.chre.sta at gmail.com Wed Feb 13 08:23:57 2008 From: wanja.chre.sta at gmail.com (Wanja Chresta) Date: Wed, 13 Feb 2008 14:23:57 +0100 Subject: regex question In-Reply-To: <287857ec-ca95-4354-b7e8-c5783974a30d@e4g2000hsg.googlegroups.com> References: <287857ec-ca95-4354-b7e8-c5783974a30d@e4g2000hsg.googlegroups.com> Message-ID: <47b2ef75_2@news.tiscalinet.ch> Hey Mathieu Due to word wrap I'm not sure what you want to do. What result do you expect? I get: >>> print m.groups() ('0021', 'xx0A', 'Siemens: Thorax/Multix FD Lab Settings Auto Window Width ', ' ', 'SL', '1') But only when I insert a space in the 3rd char group (I'm not sure if your original pattern has a space there or not). So the third group is: ([A-Za-z0-9./:_ -]+). If I do not insert the space, the pattern does not match the line. I also cant see how the format of your line is. If it is like this: line = "...Siemens: Thorax/Multix FD Lab Settings Auto Window Width..." where "Auto Window Width" should be the 4th group, you have to mark the + in the 3rd group as non-greedy (it's done with a "?"): http://docs.python.org/lib/re-syntax.html ([A-Za-z0-9./:_ -]+?) With that I get: >>> patt.match(line).groups() ('0021', 'xx0A', 'Siemens: Thorax/Multix FD Lab Settings', 'Auto Window Width ', 'SL', '1') Which probably is what you want. You can also add the non-greedy marker in the fourth group, to get rid of the tailing spaces. HTH Wanja mathieu wrote: > I clearly mark that the separator in between group 3 and group 4 > should contain at least 2 white space, but group 3 is actually reading > 3 +4 From robert.rawlins at thinkbluemedia.co.uk Wed Feb 27 05:16:33 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Wed, 27 Feb 2008 10:16:33 -0000 Subject: Logging to HTTP or File Message-ID: <007f01c87929$d46b21f0$7d4165d0$@rawlins@thinkbluemedia.co.uk> Hello Chaps, I'm after some advice on the best way to handle a logging job. Essentially I have data which I'm looking to log to a webservice, it would make good sense I think to use something like the HTTP handler for the python logging API. The problem comes when the application isn't 'online' as it were, with no network connection or if the webservice isn't currently available. In this case I don't want to simply loose all the log data, I want it stored into a file, I can then run hourly batch/cron tasks to upload to the service when the system comes back online. How would you manage this? I'm thinking about building my own custom log handler for the task, which if unable to resolve the webservice will just log to the file instead, I'm just not sure if there is a better way of achieving this, what are your thoughts? In addition to this, does anyone know which libararys the HTTP handler uses to make its call? Is it a good one which will recognise if the system has no network connection or if the server is temporarily unavailable? Is it asynchronous? Thanks for any advice guys, Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Fri Feb 29 11:30:32 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 29 Feb 2008 17:30:32 +0100 Subject: Is crawling the stack "bad"? Why? In-Reply-To: <7fc19187-2684-4831-90c4-2e4e44ee057d@i12g2000prf.googlegroups.com> References: <7xfxvhfuro.fsf@ruckus.brouhaha.com> <0ba4f68c-4046-4664-b2bb-2e8f418a5d42@41g2000hsc.googlegroups.com> <7xmyppzdoi.fsf@ruckus.brouhaha.com> <12f33c86-e1b4-45ec-8a87-d5ba7c67501d@t66g2000hsf.googlegroups.com> <7fc19187-2684-4831-90c4-2e4e44ee057d@i12g2000prf.googlegroups.com> Message-ID: <62qq98F24pse3U1@mid.uni-berlin.de> > > I will (mostly)... I knew it was bad code and a total hack, I just was > looking for a concise reason as to why. > > I appreciate the comments, guys... thanks! There is another one: crawling the stack is O(n), whilst using thread-local storage is O(1) Diez From Lie.1296 at gmail.com Sun Feb 24 13:09:37 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 24 Feb 2008 10:09:37 -0800 (PST) Subject: How about adding rational fraction to Python? References: <13a4316e-3ce7-4b3e-b418-6efb988a8845@q78g2000hsh.googlegroups.com> <676ca28c-b471-41c8-8661-fcd2ea8c23f0@i12g2000prf.googlegroups.com> <74b95b3b-1d6a-42a6-b55d-e77a868b1ffe@64g2000hsw.googlegroups.com> <70ecaf16-7308-455f-9048-730b2b2f9f2f@p43g2000hsc.googlegroups.com> <13rf9tvbkt66r2a@corp.supernews.com> <198927a7-9478-42b3-a972-82049f0130ac@u10g2000prn.googlegroups.com> <1bc9bba7-dc7f-4cfe-8e1c-fa5901c9f556@n77g2000hse.googlegroups.com> <97f30679-483d-4751-9a6e-0858b36eb426@d4g2000prg.googlegroups.com> Message-ID: On Feb 25, 12:46?am, Steve Holden wrote: > Lie wrote: > > On Feb 18, 1:25 pm, Carl Banks wrote: > >> On Feb 17, 1:45 pm, Lie wrote: > > >>>> Any iteration with repeated divisions and additions can thus run the > >>>> denominators up. ?This sort of calculation is pretty common (examples: > >>>> compound interest, numerical integration). > >>> Wrong. Addition and subtraction would only grow the denominator up to > >>> a certain limit > >> I said repeated additions and divisions. > > > Repeated Addition and subtraction can't make fractions grow > > infinitely, only multiplication and division could. > > On what basis is this claim made? > > (n1/d1) + (n2/d2) = ((n1*d2) + (n2*d1)) / (d1*d2) > > If d1 and d2 are mutually prime (have no common factors) then it is > impossible to reduce the resulting fraction further in the general case > (where n1 = n2 = 1, for example). > > >> Anyways, addition and subtraction can increase the denominator a lot > >> if for some reason you are inputing numbers with many different > >> denominators. > > > Up to a certain limit. After you reached the limit, the fraction would > > always be simplifyable. > > Where does this magical "limit" appear from? > > > If the input numerator and denominator have a defined limit, repeated > > addition and subtraction to another fraction will also have a defined > > limit. > > Well I suppose is you limit the input denominators to n then you have a > guarantee that the output denominators won't exceed n!, but that seems > like a pretty poor guarantee to me. > > Am I wrong here? You seem to be putting out unsupportable assertions. > Please justify them or stop making them. > Well, I do a test on my own fraction class. I found out that if we set a limit to the numerators and denominators, the resulting output fraction would have limit too. I can't grow my fraction any more than this limit no matter how many iteration I do on them. I do the test is by something like this (I don't have the source code with me right now, it's quite long if it includes the fraction class, but I think you could use any fraction class that automatically simplify itself, might post the real code some time later): while True: a = randomly do (a + b) or (a - b) b = random fraction between [0-100]/[0-100] print a And this limit is much lower than n!. I think it's sum(primes(n)), but I've got no proof for this one yet. From odysseus1479-at at yahoo-dot.ca Mon Feb 4 04:43:04 2008 From: odysseus1479-at at yahoo-dot.ca (Odysseus) Date: Mon, 04 Feb 2008 09:43:04 GMT Subject: Elementary string-parsing References: <60nunqF1ro06iU4@mid.uni-berlin.de> Message-ID: In article <60nunqF1ro06iU4 at mid.uni-berlin.de>, Marc 'BlackJack' Rintsch wrote: > Here and in later code you use a ``while`` loop although it is known at > loop start how many times the loop body will be executed. That's a job > for a ``for`` loop. If possible not over an integer that is used later > just as index into list, but the list itself. Here you need both, index > and objects from `names`. There's the `enumerate()` function for creating > an iterable of (index, name) from `names`. Thanks, that will be very useful. I was casting about for a replacement for PostScript's "for" loop, and the "while" loop (which PS lacks -- and which I've never missed there) was all I could come up with. > I'd put all the relevant information that describes a field of the > dictionary that is put into `found` into tuples and loop over it. There > is the cell name, the index of the cell and function that converts the > string from that cell into an object that is stored in the dictionary. > This leads to (untestet): > > def extract_data(names, na, cells): > found = dict() The problem with initializing the 'super-dictionary' within this function is that I want to be able to add to it in further passes, with a new set of "names" & "cells" each time. BTW what's the difference between the above and "found = {}"? > for i, name in enumerate(names): > data = dict() > cells_index = 10 * i + na > for cell_name, index, parse in (('epoch1', 0, parse_date), > ('epoch2', 1, parse_date), > ('time', 5, parse_number), > ('score1', 6, parse_number), > ('score2', 7, parse_number)): > data[cell_name] = parse(cells[cells_index + index]) This looks a lot more efficient than my version, but what about the strings that don't need parsing? Would it be better to define a 'pass-through' function that just returns its input, so they can be handled by the same loop, or to handle them separately with another loop? > assert name.startswith('Name: ') I looked up "assert", but all I could find relates to debugging. Not that I think debugging is something I can do without ;) but I don't understand what this line does. > found[name[6:]] = data > return found > > The `parse_number()` function could look like this: > > def parse_number(string): > try: > return float(string.replace(',', '')) > except ValueError: > return string > > Indeed the commas can be replaced a bit more elegant. :-) Nice, but I'm somewhat intimidated by the whole concept of exception-handling (among others). How do you know to expect a "ValueError" if the string isn't a representation of a number? Is there a list of common exceptions somewhere? (Searching for "ValueError" turned up hundreds of passing mentions, but I couldn't find a definition or explanation.) > > As already said, that ``while`` loop should be a ``for`` loop. But if you > put `m_abbrevs` into a `list` you can replace the loop with a single call > to its `index()` method: ``dlist[1] = m_abbrevs.index(dlist[1]) + 1``. I had gathered that lists shouldn't be used for storing constants. Is that more of a suggestion than a rule? I take it tuples don't have an "index()" method. Thanks for the detailed advice. I'll post back if I have any trouble implementing your suggestions. -- Odysseus From steve at holdenweb.com Fri Feb 15 14:35:34 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 15 Feb 2008 14:35:34 -0500 Subject: Turn off ZeroDivisionError? In-Reply-To: <46aa8fa7-36d1-4ad1-9ad5-32b32e08338f@e23g2000prf.googlegroups.com> References: <63d2e7d1-aa26-4ddc-9d12-42ae636104c1@s37g2000prg.googlegroups.com> <13qunlu5nrva731@corp.supernews.com> <13qusltq0v8vt39@corp.supernews.com> <13qv4dh7fpe0e93@corp.supernews.com> <47b50ed0$0$36357$742ec2ed@news.sonic.net> <46aa8fa7-36d1-4ad1-9ad5-32b32e08338f@e23g2000prf.googlegroups.com> Message-ID: Mark Dickinson wrote: > On Feb 14, 11:09 pm, John Nagle wrote: >> You also need to think about how conditionals interact with >> quiet NANs. Properly, comparisons like ">" have three possibilities: > > True. There was a recent change to Decimal to make comparisons (other > than !=, ==) with NaNs do the "right thing": that is, raise a Python > exception, unless the Invalid flag is not trapped, in which case they > return False (and also raise the Invalid flag). I imagine something > similar would make sense for floats. > >> True, False, and "raise". Many implementations don't do that well, >> which means that you lose trichotomy. "==" has issues; properly, >> "+INF" is not equal to itself. > > I don't understand: why would +INF not be equal to itself? Having > INF == INF be True seems like something that makes sense both > mathematically and computationally. > [...] There are an uncountable number of infinities, all different. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From python at rcn.com Thu Feb 7 17:13:00 2008 From: python at rcn.com (Raymond Hettinger) Date: Thu, 7 Feb 2008 14:13:00 -0800 (PST) Subject: index() of sequence type? References: <610fi0F1s9rvpU2@mid.uni-berlin.de> Message-ID: On Feb 7, 1:57 pm, "Gabriel Genellina" wrote: > Tuples are worse: they implement > __contains__ but not index. So you can say: > > py> 2 in (1,2,4,8) > True > > but not: > > py> (1,2,4,8).index(2) You must be using an old version of Python like 2.5 ;-) As of yesterday, Py2.6 has tuple.index() and tuple.count(). Python 2.6a0 (trunk:60638M, Feb 6 2008, 18:10:45) [GCC 4.1.1 (Gentoo 4.1.1)] on linux2 >>> (1,2,4,8).index(2) 1 Raymond From lists at cheimes.de Tue Feb 19 11:01:05 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 19 Feb 2008 17:01:05 +0100 Subject: Seemingly odd 'is' comparison. In-Reply-To: <3145ed12-d0e3-4d3a-9cb7-91efa6f17edb@d4g2000prg.googlegroups.com> References: <47b36135$0$26076$88260bb3@free.teranews.com> <13rk2ho7b8h1c85@corp.supernews.com> <8cafcd9e-6a61-483f-b8f3-6e7b0e5ab435@s8g2000prg.googlegroups.com> <3145ed12-d0e3-4d3a-9cb7-91efa6f17edb@d4g2000prg.googlegroups.com> Message-ID: Asun Friere wrote: > So was that a yes or no? I mean is it even possible for the identity > behaviour of mutables to vary between implementations? I can't see > how they can possibly be interned, but is there some other factor I'm > missing in regard to identity behaviour which could in fact vary > between implementations? In CPython some strings are interned (see the intern builtin). The free list of lists, tuples, dict and the block allocation of ints and floats can have an interning like effect, too. IronPython and Jython may not have interning or free list at all. Even in CPython the interning and free lists are an implementation detail that may chance between releases. In a matter of fact I'm messing around with free lists to speed up Python 2.6/3.0 and to give back memory earlier. Christian From cfbolz at gmx.de Wed Feb 6 13:16:48 2008 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Wed, 06 Feb 2008 19:16:48 +0100 Subject: Why not a Python compiler? In-Reply-To: References: <28eead2f-a40c-414b-bd3d-a941f8a851a2@d70g2000hsb.googlegroups.com> <7da40f42-f64f-4939-a0dc-d24d1ff85f2d@v4g2000hsf.googlegroups.com> <47A9EB00.6000703@gmx.de> Message-ID: <47A9F990.2080703@gmx.de> Hi Luis, Luis M. Gonzalez wrote: > Well, lets suppose that being faster than C is the real goal... How about we call it a very long-term dream? > Are you confident that it will be reached? We have ideas how to get there, but it is really rather long-term. There will be a lot of research needed to achieve that for sure. > How far is it at this moment? Since a year already we have a JIT that makes quite fast code for purely integer-type operations. Quite fast meaning about the speed of gcc -O0. So far it is not faster than Psyco (it supports generators, though). We are confident that the JIT will get substantially better this year (probably better than Psyco). Where exactly this will leave us we don't know. > I've been following the project but the scarcity of news is getting me > anxious... Read the blog: morepypy.blogspot.com :-) Cheers, Carl Friedrich From jeffrey at fro.man Sat Feb 2 11:10:14 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Sat, 02 Feb 2008 08:10:14 -0800 Subject: string split without consumption References: Message-ID: <13q95f6c73f70df@corp.supernews.com> robert wrote: > thanks. Yet this does not work "naturally" consistent in my line > processing algorithm - the further buffering. Compare e.g. > ss.split('\n') ?.. > > >>> 'owi\nweoifj\nfheu\n'.split('\n') > ['owi', 'weoifj', 'fheu', ''] > >>> 'owi\nweoifj\nfheu\nxx'.split('\n') > ['owi', 'weoifj', 'fheu', 'xx'] Maybe this works for you? >>> re.split(r'(\n)', ss) ['owi', '\n', 'weoifj', '\n', 'fheu', '\n', ''] Jeffrey From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Feb 13 20:04:42 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 14 Feb 2008 02:04:42 +0100 Subject: Floating point bug? References: Message-ID: <61hidaF1u9m5iU1@mid.individual.net> robinsiebler at gmail.com wrote: > I've never had any call to use floating point numbers and now that > I want to, I can't! Ever considered phrasing your actual problem so one can help, let alone looking at the archive for many, many postings about this topic? Regards, Bj?rn -- BOFH excuse #66: bit bucket overflow From gslindstrom at gmail.com Sun Feb 3 17:08:00 2008 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Sun, 3 Feb 2008 16:08:00 -0600 Subject: PyCon 2008 Tutorial Sessions Message-ID: Registration for PyCon 2008 is now open. Held in Chicago March 14-16 with "Tutorial Thursday" on March 13 and sprints afterwards, it is expected that nearly 800 Python enthusiasts will attend at least part of the conference. It is totally run by volunteers and is affordable for just about anyone. I would like to point out the tutorial sessions being offered; all the way from "Python for the Absolute Beginner", to advanced courses on optimizing Python programs (with 27 more classes in between). Click on over to http://us.pycon.org/2008/about/ for information about the conference. Here is a list of the classes being offered along with the instructors scheduled to present the classes (click to get more information on a session). It's a great way to learn more Python. *Morning Session* (9:00am-12:20pm) - Eggs and Buildout Deployment in Python(Jeff Rush) - Python 101 for Programmers(Steve Holden) - Introduction to SQLAlchemy(Jonathan Ellis and Michael Bayer) - Python plotting with matplotlib and pylab(John Hunter) - SWIG Master Class (David Beazley) - Secrets of the Framework Creators(Feihong Hsu and Kumar McMillan) - Introduction to NumPy(Travis Oliphant and Eric Jones) - Making Small Software for Small People, Sugar/OLPC Coding by Example(Mike C. Fletcher) - Hands-on Python for the Absolute Beginner I(Dr. Andrew Harrington) *Afternoon Session* (1:20pm-4:40pm) - Python 101 (Stuart Williams) - Getting Started with Pylons/TurboGears2 & WSGI: Modern Python Web Development (Mark Ramm and Ben Bangert) - Advanced SQLAlchemy(Jonathan Ellis and Michael Bayer) - Django Tutorial (Jacob Kaplan-Moss) - wxPython I: Intro to GUI Programming with wxPython and MVC(David Goodger) - Faster Python Programs through Optimization and Extensions I(Mike M?ller) - Tools for Scientific Computing in Python(Travis Oliphant and Eric Jones) - Generator Tricks for Systems Programmers(David Beazley) - Basic Python for Java Programmers(Alex Martelli and Anna Ravenscroft) - Hands-on Python for the Absolute Beginner II(Dr. Andrew Harrington) *Evening Session* (6:10pm-9:30pm) - Python 102 (Stuart Williams) - Mastering Pylons and TurboGears 2: Moving Beyond the Basics.(Mark Ramm, Ben Bangert) - Practical Applications of Agile (Web) Testing Tools(C. Titus Brown and Grig Gheorghiu) - Django Code Lab (Jacob Kaplan-Moss, Adrian Holovaty and James Bennett) - wxPython II: Advanced GUI Programming with wxPython and MVC(David Goodger) - Faster Python Programs through Optimization and Extensions II(Mike M?ller) - Automating Windows Applications with win32com(Roy H. Han) - Internet Programming with Python(Wesley J. Chun) - Tail Wags Fangs: What Python Developers Should Know About Plone(Rob Lineberger) - Pygame: Modern game development(Noah Kantrowitz and Marc Destefano) -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Fri Feb 1 05:57:22 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 01 Feb 2008 05:57:22 -0500 Subject: PLEASE ACCEPT MY SINCERE APOLOGIES In-Reply-To: References: <1b443287-9ca6-44cb-a230-08b3bbb92416@i12g2000prf.googlegroups.com> <1a2c3942-ba50-4378-96d7-9e6adb188536@j78g2000hsd.googlegroups.com> Message-ID: Eduardo O. Padoan wrote: > On Feb 1, 2008 5:19 AM, Arnaud Delobelle wrote: >> On Feb 1, 5:08 am, Paddy wrote: >>> On Feb 1, 1:26 am, "Blubaugh, David A." wrote: >>> >>> >>> >>>> To Everyone on the planet Earth, >>>> Please accept my apologies for >>>> Why the Hell has nobody answered my question!!!!!!!!!!!!!!!!!!!!. >>>> I am just trying to finish a Masters thesis that is quite beyond >>>> anything in this world. >>>> David Blubaugh >>>> -----Original Message----- >>>> From: python-list-bounces+dblubaugh=belcan.... at python.org >>>> [mailto:python-list-bounces+dblubaugh=belcan.... at python.org] On Behalf >>>> Of python-list-requ... at python.org >>>> Sent: Thursday, January 31, 2008 7:30 PM >>>> To: python-l... at python.org >>>> Subject: Python-list Digest, Vol 53, Issue 2 >>>> Send Python-list mailing list submissions to >>>> python-l... at python.org >>>> To subscribe or unsubscribe via the World Wide Web, visit >>>> http://mail.python.org/mailman/listinfo/python-list >>>> or, via email, send a message with subject or body 'help' to >>>> python-list-requ... at python.org >>>> You can reach the person managing the list at >>>> python-list-ow... at python.org >>>> When replying, please edit your Subject line so it is more specific than >>>> "Re: Contents of Python-list digest..." >>>> This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. >>> Could you now specifically apologize for all those question >>> marks!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! >>> >>> :-) >>> >>> Peace, Paddy. >> And for top-posting :) > > And for using ALL CAPS :) > >> -- >> Arnaud > AND THEN WE WILL ACCEPT YOUR APOLOGY!!!!!!!!!!!!! Seriously, we all suffer from the same frustrations as you appear to have here from time to time, but you would do well to remember a few things: 1. Google has a very long memory. You may cringe when you see this thread in five years. 2. There *are* accepted standards of behavior in most newsgroups, and because they are usually community-defined it's as well to take a lead form the natives, and to lurk for a while then start gently. 3. It's usually best to avoid thinking that you are being deliberately ignored in these circumstances, even though the urgency of a specific situation can induce paranoia. Anyway, welcome to c.l.py. After this baptism by fire I am sure it will all be plain sailing from here on:-) regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From jjkk73 at gmail.com Wed Feb 20 06:15:57 2008 From: jjkk73 at gmail.com (jorma kala) Date: Wed, 20 Feb 2008 12:15:57 +0100 Subject: Automating GUI interaction with Python Message-ID: Hi, Is there a python library or bindings to a library in some other language for automating GUI interaction (the kind of functionality provided by Autoit for instance). What I need to do is very simple GUI automation : moving the mouse cursor to and from specified screen coordinates, clicking, etc. Thanks a lot. -------------- next part -------------- An HTML attachment was scrubbed... URL: From lanwrangler at gmail.com Thu Feb 7 04:57:31 2008 From: lanwrangler at gmail.com (lanwrangler at gmail.com) Date: Thu, 7 Feb 2008 01:57:31 -0800 (PST) Subject: Suggestions for structure of HTML-generating app References: <4e49c030-d79e-4aef-9f26-f4aecfe2e159@j20g2000hsi.googlegroups.com> Message-ID: On Feb 5, 9:14 pm, Bernard wrote: > On 5 f?v, 10:09, "lanwrang... at gmail.com" > wrote: > > > Are there any good approaches of doing this kind of thing that I've > > missed, or am I resigned to having HTML and Python code mixed and so > > will just have to keep all that nastiness to as few modules as > > possible? > > > Thanks, > > Matthew. > > we use Cheetah templates to do just that at my workplace. > we use CherryPy to generate the data and then we pass it on > to the Cheetah template which handles the data and add html over it. > here's an article on that matter :http://www.onlamp.com/pub/a/python/2005/01/13/cheetah.html Thanks for the pointer to Cheetah. At first glance it looks neat. Cherrytemplate has done well for me so far but I don't think it's under active development any more so it may be time to migrate. Matthew. From dg.google.groups at thesamovar.net Thu Feb 14 16:09:10 2008 From: dg.google.groups at thesamovar.net (dg.google.groups at thesamovar.net) Date: Thu, 14 Feb 2008 13:09:10 -0800 (PST) Subject: How to tell if I'm being run from a shell or a module References: <44e07112-e3f5-4446-8522-24c2476efd4a@e10g2000prf.googlegroups.com> Message-ID: <9ec4f650-38bb-43e6-a78e-e0b4f1b658dc@e6g2000prf.googlegroups.com> Thanks for the replies, but it's not what I meant. What I want to be able to determine is whether or not the user is running from an interactive shell (like IPython or IDLE). Checking if __name__=='__main__' checks if the current module is the one being run, but suppose you have two modules A and B, with the function f defined in module B that should print 'Interactive' or 'Module' say. The module A just consists of: import B; B.f(). Now whenever f is called, __name__ will not be '__main__' for it. Someone using IDLE could write import B then B.f() too. The question is: is there a way for f to determine if someone was using an interactive shell to call it or if it was being called some other way. The way I came up with works in these limited cases but won't work in a more general situation (but perhaps there is no way for it to know in the more general situation). Dan On Feb 14, 7:01 pm, Chris wrote: > If you're just trying to prevent some actions from happening if > something loads your script as a module just put the 'action items' > under an if like: > if __name__ == '__main__': > do_the_cool_stuff() > > All your functions inside the file will remain in-tact but it won't > execute anything. From mahs at telcopartners.com Thu Feb 7 12:51:36 2008 From: mahs at telcopartners.com (Michael Spencer) Date: Thu, 07 Feb 2008 09:51:36 -0800 Subject: Why does list have no 'get' method? In-Reply-To: <47ab1d00$0$25367$9b4e6d93@newsspool4.arcor-online.net> References: <95d6e98c0802060253gde6233cn97d42c344b382416@mail.gmail.com> <7xzlud9sof.fsf@ruckus.brouhaha.com> <36d4dbb4-bf0a-4a1a-8c93-f6636434fd0b@v67g2000hse.googlegroups.com> <2c5efd38-960d-45f5-98e9-4c4fbde5fd38@j20g2000hsi.googlegroups.com> <47ab1d00$0$25367$9b4e6d93@newsspool4.arcor-online.net> Message-ID: Wildemar Wildenburger wrote: > Arnaud Delobelle wrote: >> Personally, between >> >> * foo if foo else bar >> * foo or bar >> >> I prefer the second. Maybe it could be spelt >> >> * foo else bar ? >> > How about > > val = foo rather than bar > > If that is not clear and obvios, I don't know what is. ;) > > /W Excellent suggestion, and obviously its semantics should be: val = foo if bar else foo and so, some might argue for: val = foo despite bar which would allow more aggressive short-circuiting. However, I'm not sure how useful this is in practice. M From lists at cheimes.de Mon Feb 4 10:29:05 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 04 Feb 2008 16:29:05 +0100 Subject: Getting Python to fork? In-Reply-To: References: <4a32de90-dbdd-49da-ab17-93037d3229f7@p69g2000hsa.googlegroups.com> Message-ID: Jon Ribbens wrote: > I think that's changing Python's idea of stdin etc but not the > operating system's idea of them. You won't be closing the original > file descriptors, and if you run any subprocesses they will end up > with the original stdin/out/err. Unless sys.stdin is more magic > than I'm aware of. Jon is correct here. You must close or redirect the underlying C file descriptor. Python's sys.std streams don't magically do this for you because Python keeps a backup of the standard streams for internal purpose in sys.__std*__. os.dup2 is the best solution. Christian From szekeres at iii.hu Tue Feb 19 09:01:18 2008 From: szekeres at iii.hu (=?UTF-8?Q?Szekeres_Istv=C3=A1n?=) Date: Tue, 19 Feb 2008 15:01:18 +0100 Subject: Python seems to be ignoring my except clause... In-Reply-To: <7c1ab99b-844d-43d4-8c54-8a07d223d37c@u72g2000hsf.googlegroups.com> References: <7c1ab99b-844d-43d4-8c54-8a07d223d37c@u72g2000hsf.googlegroups.com> Message-ID: Hi Adam, def characters(self, string): > Please note that "string" is also a name of a very commonly used module so it is not advised to use as a local variable name. Istvan -------------- next part -------------- An HTML attachment was scrubbed... URL: From dblubaugh at belcan.com Mon Feb 18 12:31:44 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Mon, 18 Feb 2008 12:31:44 -0500 Subject: Python 3.0 In-Reply-To: <895f1790802151644q70c6cec6k946b4185cb2ddc13@mail.gmail.com> References: <27CC3060AF71DA40A5DC85F7D5B70F38026E5A52@AWMAIL04.belcan.com> <895f1790802151602r354bffb4pcca979c9316fecf8@mail.gmail.com> <27CC3060AF71DA40A5DC85F7D5B70F38026E5A7F@AWMAIL04.belcan.com> <895f1790802151644q70c6cec6k946b4185cb2ddc13@mail.gmail.com> Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F38026E5E6E@AWMAIL04.belcan.com> Is there a logical reason why Python 3 is not backwards compatible? David Blubaugh -----Original Message----- From: Bill Hart [mailto:goodwillhart at googlemail.com] Sent: Friday, February 15, 2008 7:44 PM To: Blubaugh, David A. Subject: Re: scary thought for consideration I don't know, it's in alpha now apparently and is not backwards compatible. Bill. On 16/02/2008, Blubaugh, David A. wrote: > When will Python 3 be available? > > Thanks, > > David > > > > > -----Original Message----- > From: Bill Hart [mailto:goodwillhart at googlemail.com] > Sent: Friday, February 15, 2008 7:03 PM > To: Blubaugh, David A. > Subject: Re: scary thought for consideration > > No it should be fine. Python 3 might cause problems. > > On 15/02/2008, Blubaugh, David A. wrote: > > > > > > > > To All, > > > > > > I am wondering as far as the integration of MyHDL with Python 2.5, > > if there might be any potential version incompatibility issues? > > What I mean is will MyHDL not operate correctly, if it is executed > > with a Python 2.5 version not a Python 2.4? I will be testing to see > > if this possibility is indeed true over the weekend. > > > > > > Thanks, > > > > David Blubaugh > > > > This e-mail transmission contains information that is confidential > > and > may > > be privileged. It is intended only for the addressee(s) named above. > If > > you receive this e-mail in error, please do not read, copy or > > disseminate it in any manner. If you are not the intended recipient, > > any disclosure, copying, distribution or use of the contents of this > > information is prohibited. Please reply to the message immediately > > by informing the sender that the message was misdirected. After > > replying, > > > please erase it from your computer system. Your assistance in > correcting this error is appreciated. > > > From bignose+hates-spam at benfinney.id.au Tue Feb 12 19:02:02 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 13 Feb 2008 11:02:02 +1100 Subject: ways to declare empty set variable References: <56a14$47b1a306$839b8704$9583@news2.tudelft.nl> <5099c$47b1a77b$839b8704$11089@news2.tudelft.nl> <7xhcgd7tof.fsf@ruckus.brouhaha.com> <719e7c26-7d52-4b78-875c-fc7d5ca32f4e@s19g2000prg.googlegroups.com> <874pcdzsho.fsf@benfinney.id.au> Message-ID: <87zlu5yb9h.fsf@benfinney.id.au> Steve Holden writes: > Ben Finney wrote: > [...] > > > > Note that '()' is syntactically null. Parentheses don't declare a > > tuple literal, commas do. Parentheses are for grouping within > > expressions, not specifying type. > > > Tell that to the interpreter: > > >>> type(()) > > >>> tuple() is () > True > >>> Well, knock me down with a kipper. That makes it even more a violation of principle-of-least-astonishment that the '(foo)' form doesn't give a one-element tuple literal. -- \ "If consumers even know there's a DRM, what it is, and how it | `\ works, we've already failed." ?Peter Lee, Disney corporation, | _o__) 2005 | Ben Finney From sjmachin at lexicon.net Mon Feb 25 17:14:30 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 25 Feb 2008 14:14:30 -0800 (PST) Subject: float / rounding question References: Message-ID: <623400c9-3cd8-40cf-9841-522535604a01@s19g2000prg.googlegroups.com> On Feb 26, 7:14 am, "Terry Reedy" wrote: > wrote in message > > news:d4d9e9d6-b0e0-4063-a5b2-456bcea5a6ce at z17g2000hsg.googlegroups.com... > | Hi I'm very much a beginner with Python. > | I want to write a function to convert celcius to fahrenheit like this > | one: > | > | def celciusToFahrenheit(tc): > | tf = (9/5)*tc+32 > | return tf > > Unless you are importing 'integer division' or using 3.0, that should be > 9.0/5.0. Has the syntax changed? I thought it was: from __future__ import division The OP may wish to avoid the confusion and the pointless division by using: tf = 1.8 * tc + 32 > > | I want the answer correct to one decimal place, so > | celciusToFahrenheit(12) would return 53.6. > > As written, running above on 2.x returns 44. > > tjr From AWasilenko at gmail.com Sat Feb 16 14:08:59 2008 From: AWasilenko at gmail.com (Adam W.) Date: Sat, 16 Feb 2008 11:08:59 -0800 (PST) Subject: How do I use SendInput in Python? Message-ID: <6647346d-3c38-47a4-ae56-6df3ccec7b01@62g2000hsn.googlegroups.com> I'm at the last stage of my project and the only thing left to do is trigger a mouse click. I did some searching around for example code and stumped upon SendInput http://msdn2.microsoft.com/en-us/library/ms646310.aspx . However I was not able to find example code for python USING SendInput, and I have zero ability to make C work (or whatever that is written in). Can someone help me use SendInput in python, or point me to an alternative method? From stefan_ml at behnel.de Mon Feb 11 05:02:38 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 11 Feb 2008 11:02:38 +0100 Subject: How to convert markup text to plain text in python? In-Reply-To: References: Message-ID: <47B01D3E.3010300@behnel.de> geoffbache wrote: > I have some marked up text and would like to convert it to plain text, > by simply removing all the tags. Of course I can do it from first > principles but I felt that among all Python's markup tools there must > be something that would do this simply, without having to create an > XML parser etc. > > I've looked around a bit but failed to find anything, any tips? > > (e.g. convert "Today is Friday" to "Today is Friday") This might be of interest: http://pypi.python.org/pypi/haufe.stripml Stefan From stefan_ml at behnel.de Sun Feb 3 14:42:45 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 03 Feb 2008 20:42:45 +0100 Subject: GUI definition for web and desktop In-Reply-To: References: Message-ID: <47A61935.2000407@behnel.de> Daniel Fetchinson wrote: > I'm looking for a simple text based GUI definition format and > associated python modules to work with it that is capable of defining > simple GUI's for *both* the web and the desktop. I have an application > that is accessible through the web and also through desktop > applications and both clients should be presented a simple dialog GUI. [...] > I haven't yet decided on the desktop client GUI library, it depends on > which library has such a dynamically generatable interface from a text > file. But it should be cross platform between linux and windows. That sounds a lot like XUL to me. That's the language that Mozilla browsers use for their GUI. AFAIR, it had Python bindings through XPCOM the last time I looked into it. http://www.mozilla.org/why/framework.html On the other hand, if you want pure HTML for your web app, maybe you should consider making the desktop app HTML-based, too? Stefan From deets at nospam.web.de Tue Feb 5 10:12:14 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 05 Feb 2008 16:12:14 +0100 Subject: boolean decisions References: <75aff233-fc8c-4e2e-bfb5-daf6a13bc932@i12g2000prf.googlegroups.com> Message-ID: <60rcmeF1ro45mU1@mid.uni-berlin.de> > I think the problem is actually less simple than that. Although they can > enumerate many or all of the rows of the table I suspect that the business > people don't always know why they choose particular outcomes; often > they're not looking at most of the input choices at all they just > concentrate on one or other. If they could formulate the rules properly > they would, but somehow they can't. > > If I can obtain some simplified rules for the two or three outputs and > present them to the business guys they may actually be able to confirm > their own original choices/and or reject/confirm the rule. Maybe creating descision trees from real-world data might also be a way to infer the business-rules. Diez From stelevision79 at gmail.com Fri Feb 29 02:43:30 2008 From: stelevision79 at gmail.com (stelevision) Date: Thu, 28 Feb 2008 23:43:30 -0800 (PST) Subject: Registry and Spyware Cleaner (Free Download) Message-ID: Netcom3(tm) is a recognized global leader in internet security software. With Netcom3 Internet Security Suite, it's key focus is on securing sensitive consumer online interactions, as well as prevent and remove Spyware, Adware, optimize, fix PC errors, and make your system run faster and error free. Netcom3 Internet Security Software will speed up your computer, detects and removes spyware and adware, Viruses, Trojans, Dialers, Worms and a host of other dangerous parasites. It automatically detects and corrects the most common problems including: run time errors, corrupt files, invalid paths, fonts, file types, CLSID, DLLs, sound, help files, shell extensions, AppEvents, class keys and many more. Just like with a car your PC needs software maintenance to keep it running smoothly like the first time you booted your pc. A common cause of Windows crashes, error messages and performance problems are the result of registry inconsistencies. Netcom3(tm) Windows registry cleaner can fix these problems for you and make your PC run smoothly again. Firewall and a good anti-virus product are important. But these alone won't protect you from intrusive spyware or keep your PC optimized for peak performance. This is why Netcom3 Internet Security Suite has been developed to be the perfect support for Windows PCs. Please click the link below for further details:- http://shajiashi.netwire.hop.clickbank.net From steve at holdenweb.com Fri Feb 1 22:48:04 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 01 Feb 2008 22:48:04 -0500 Subject: urllib supports javascript In-Reply-To: <47A3D051.2050108@block.duxieweb.com> References: <47A3D051.2050108@block.duxieweb.com> Message-ID: J. Peng wrote: > hello, > > Which useragent lib supports javascript? > I know something about these libs: urllib,urllib2,cookielib,httplib > But I'm not sure which one of them can support javascript scripts. > Thanks! None of them do. Javascript support is a very complex task! I believe there have been efforts to harness the spidermonkey code base [1] but they date back to Python 2.3. It may be that the IronPython environment has more to offer, especially now that DLR support is specifically intended to promote interaction and information exchange between code in different languages, but that is oure speculation on my part. regards Steve [1]: http://wwwsearch.sourceforge.net/python-spidermonkey/ -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From qgallet at gmail.com Fri Feb 15 11:58:22 2008 From: qgallet at gmail.com (Quentin Gallet-Gilles) Date: Fri, 15 Feb 2008 17:58:22 +0100 Subject: Solve a Debate In-Reply-To: References: Message-ID: <8b943f2b0802150858r13cd6b02i64a6a7f90cbc2b45@mail.gmail.com> If the data becomes much bigger, change your way of storing it, not the code. You don't want to code hundreds of "if - elif - else" because you have hundreds of different data, right ? TheDailyWTF is full of horror stories like this, by the way ;-) Data growth shouldn't result in modification in logic code. Also I find that avoiding conditionals is always a win. That's in the spirit of the pythonic way of removing what would be an if-elif chain (or a switch statement in another language) by a dict-based dispatch. Returning to your month exercise... Since "code is data", assigning the numbers of days or comparing the month number in if statements is basically the same. In the end, you have twelve different values stored in one way or another in your program and loaded in RAM at execution time. Therefore, I find the array solution (or whatever storage you wish to use) better by all counts. Cheers, Quentin On Fri, Feb 15, 2008 at 5:24 PM, nexes wrote: > Alright so me and my friend are having argument. > > Ok the problem we had been asked a while back, to do a programming > exercise (in college) > That would tell you how many days there are in a month given a > specific month. > > Ok I did my like this (just pseudo): > > If month = 1 or 3 or etc .... > noDays = 31 > Elseif month = 4 or 6 etc .... > noDays = 30 > Else > noDays = 29 > (we didn't have to take into account a leap year) > > He declared an array and assigned the number of days in a month to its > own element in an array. Now > I realise that in this example it would not make a difference in terms > of efficiency, but it is my belief that if > there is more data that needed to be assigned(i.e. a couple megs of > data) it would be simpler (and more efficient) to > do a compare rather then assigning all that data to an array, since > you are only going to be using 1 value and the rest > of the data in the array is useless. > > What are everyone else's thoughts on this? > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Fri Feb 22 10:52:44 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 22 Feb 2008 15:52:44 GMT Subject: Return value of an assignment statement? References: <6d945394-739e-4c47-ad71-faaab8f9d566@34g2000hsz.googlegroups.com> <5sudnTSXrZY0aCDanZ2dnUVZ_rKtnZ2d@comcast.com> <5MSdncSVGdGriCPanZ2dnUVZ_vPinZ2d@comcast.com> <627eg8F21f45aU1@mid.uni-berlin.de> <13rtg6a341gqg5e@corp.supernews.com> Message-ID: <6289ecF21f45aU4@mid.uni-berlin.de> On Fri, 22 Feb 2008 12:32:10 +0000, Steven D'Aprano wrote: > On Fri, 22 Feb 2008 08:12:56 +0000, Marc 'BlackJack' Rintsch wrote: > >> A "variable" in programming languages is composed of a name, a memory >> location, possibly a type and a value. In C-like languages, where you >> put values in named and typed "boxes", the memory location and type are >> attached to the name. In Python both belong to the value. > > But Python objects don't have names, so by your own definition, they > aren't variables. Exactly! Names aren't variables. The unit of a name, an address, and a value are a variable. > Names are associated with namespaces, not objects. A name must have one > and only one object bound to it at any one time; What is a binding when it's not an association between a name and an object!? So names are associated with objects. There are no names without objects in Python. If a name is not bound to any object, how could the name exist? That would be like a dangling pointer, a beast that doesn't exists in Python. Okay there are local names that are known and therefore somehow "exist" before they get bound, but that's IMHO an implementation detail. > objects on the other hand can be bound to one name, or no name, or a > thousand names. The object itself has no way of knowing what names it is > bound to, if any. > > Or, to put it another way... Python doesn't have variables. It has. You just can't substitute the term "name" with "variable" and expect it to behave like in C. A variable is not just the name but also the value and the storage space and how those are connected. Ciao, Marc 'BlackJack' Rintsch From info at thegrantinstitute.com Mon Feb 18 03:53:46 2008 From: info at thegrantinstitute.com (Anthony Jones) Date: 18 Feb 2008 00:53:46 -0800 Subject: Professional Grant Proposal Writing Workshop (June 2008: Seattle, Washington) Message-ID: <20080218005346.A43538967CA7BBA9@thegrantinstitute.com> An HTML attachment was scrubbed... URL: From aaron.watters at gmail.com Tue Feb 26 09:35:21 2008 From: aaron.watters at gmail.com (Aaron Watters) Date: Tue, 26 Feb 2008 06:35:21 -0800 (PST) Subject: Article of interest: Python pros/cons for the enterprise References: <2f1527a7-2f66-44c7-9665-4d8ff01fa5ab@28g2000hsw.googlegroups.com><47bd4a24$0$25225$426a74cc@news.free.fr> <036e93e6-5840-4a3c-8642-67a0a9ec44f2@i7g2000prf.googlegroups.com> <784ec210-f389-4a15-b458-961100de9103@v3g2000hsc.googlegroups.com> <5d351937-e1bc-44ab-810d-11f226793b2e@b29g2000hsa.googlegroups.com> Message-ID: <6736c4f5-8628-40b8-b898-2f6460822409@41g2000hsc.googlegroups.com> On Feb 25, 8:29 am, Nicola Musatti wrote: > > And the migration to Python is due in large part because of an > > additional factor of 3-4x in personal productivity (over Java). > > Improvements in runtime performance wouldn't hurt, but for many > > applications that's not an issue. (If optional data typing were > > offered, Python's penetration in the enterprise space would be even > > higher, and I suspect there would be performance gains as well.) > > This I found less hard to believe. Python is more expressive than Java > and usually requires less code for the same task. Moreover the > availability of libraries is comparable. I tend to cheat when I code in java and pretend I'm writing in Python. But even then the biggest pain comes in when I try to use really advanced data structures and get all knotted up in the verbosity -- and when I try to figure out what I was doing later it's even worse. For example in Python I tend to build things like dictionaries of tuples to lists of dictionaries without thinking about it, but in Java the equivalent of D[ (x,y) ] = [ { a: b } ] is too horrible to be imagined, even if you cheat and use the non-type-safe containers. Of course this is in addition to other Java annoyances like no proper support for multivalued returns or function pointers, and overgeneralized libraries. However, I have found in the corporate environment that managers frequently don't like it when you do in a few days that things that they themselves don't know how to do in less than several months. Especially when it makes the other programmers angry. Sometimes I think programmers should get sociology/psychology/poli.sci degrees and pick up the programming stuff on the job, since most of what counts seems to be politics, really. -- Aaron Watters === http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=spam+eggs From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Feb 19 10:47:01 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 19 Feb 2008 16:47:01 +0100 Subject: Linux/Python Issues References: Message-ID: <620bvlF218ub0U1@mid.individual.net> MartinRinehart at gmail.com wrote: > Both GNOME and KDE put Windows to shame. An old Windows guy, like > me, can just start using either one without needing 'common *n*x > knowledge.' Sure, go and compile them from the sources. The X server too, please (I got half insane from that once). > Too bad the *n*x community isn't more welcoming to outsiders. I think the automobile community could be more welcoming to outsiders either. I just can refill fuel and perhaps change motor oil, but assembling a car from its components is too hard for me. Evil automobilers, why do they make it so complicated! 8) Regards, Bj?rn -- BOFH excuse #362: Plasma conduit breach From mensanator at aol.com Tue Feb 5 17:35:53 2008 From: mensanator at aol.com (mensanator at aol.com) Date: Tue, 5 Feb 2008 14:35:53 -0800 (PST) Subject: IronPython vs CPython: faster in 1.6 times? References: <52c34392-5c5b-49b8-8c75-ba9add438b73@k39g2000hsf.googlegroups.com> <2995994a-487c-4797-ad01-0989cd9ea40a@l16g2000hsh.googlegroups.com> Message-ID: On Feb 5, 3:56?pm, Arnaud Delobelle wrote: > On Feb 5, 8:01?pm, Istvan Albert wrote: > > > > > > > On Feb 5, 12:31 pm, dmitrey wrote: > > > > Hi all, > > > the urlhttp://torquedev.blogspot.com/2008/02/changes-in-air.html > > > (blog of a game developers) > > > says IronPython is faster than CPython in 1.6 times. > > > Is it really true? > > > This is a second time around that IronPython piqued my interest > > sufficiently to create a toy program to benchmark it and I must say > > the results are not encouraging: > > > $ python bench.py > > Elapsed time: 1.10 s > > > $ ipy bench.py > > Elapsed time:65.01 s > > > and here is the benchmark program: > > > import time > > start = time.time() > > > def foo(a): > > ? ? return a * a > > > data = {} > > for i in xrange( 10**6 ): > > ? ? data[i] = foo(i) > > > print 'Elapsed time:%5.2f s' % ( time.time() - start) > > Could it be because .NET doesn't have arbitrary length integer types A good reason to not use it. > and your little benchmark will ?create lots of integers > 2**32 ? > What is the result if you replace foo(a) with > > def foo(a): return sqrt(a) > > -- > Arnaud- Hide quoted text - > > - Show quoted text - From emetsger at obj-sys.com Thu Feb 28 12:49:54 2008 From: emetsger at obj-sys.com (Ethan Metsger) Date: Thu, 28 Feb 2008 12:49:54 -0500 Subject: Decorators and buffer flushing Message-ID: Hi, all. I apologize for what is perhaps a newb question. I'm in the process of transitioning our testing framework from Perl to Python. While that alone probably sets off some red flags, I'm afraid it's what I'm stuck with. I'm modeling a test with five operations: build, execute, validate, publish, and clean. The main loop might look something like this: with Test(...) as t: t.build() t.execute() t.validate() t.publish() At each run, I want to output a '.' to denote completion of that test step. I've been able to do this, sort of, using the following decorator (edited for brevity): def report(f): def new(self): stat = f(self); if stat is True: sys.stdout.write ('.') else: ... sys.stdout.flush() return new (Each one of the test functions returns True or False depending on its completion status.) The problem is that rather than outputting a period after each step is completed, it outputs all four of them at once. Instead of seeing progress as it happens, I get it when it's finished, even though I'm flushing the output buffer. Any thoughts? Best, Ethan (emetsger at obj-sys.com) http://uppertank.net/ethanm/ From russandheather at gmail.com Mon Feb 25 02:33:18 2008 From: russandheather at gmail.com (Russell Warren) Date: Sun, 24 Feb 2008 23:33:18 -0800 (PST) Subject: Is crawling the stack "bad"? Why? References: <7xfxvhfuro.fsf@ruckus.brouhaha.com> Message-ID: <0ba4f68c-4046-4664-b2bb-2e8f418a5d42@41g2000hsc.googlegroups.com> > That is just madness. What specifically makes it madness? Is it because sys._frame is "for internal and specialized purposes only"? :) > The incoming ip address is available to the request handler, see the > SocketServer docs I know... that is exactly where I get the address, just in a mad way. > Write a request handler that stashes that info somewhere that rpc > responders can access it in a sane way. That is exactly where I started (creating my own request handler, snagging the IP address and stashing it), but I couldn't come up with a stash location that would work for a threaded server. This is the problem I was talking about with the "current_peer_info" scheme. How is the RPC responder function supposed to know what is the right stash, given that when threaded there could be multiple stashes at a time? The IP needs to get down to the exact function execution that is responding to the client... how do I do that? I had my options as: 1) stash the IP address somewhere where the RPC function could get it 2) pass the IP down the dispatch chain to be sure it gets to the target I couldn't come up with a way to get 1) to work. Then, trying to accomplish 2) I reluctantly started messing with different schemes involving my own versions of do_POST, _marshaled_dispatch, and _dispatch in order to pass the IP directly down the stack. After some pain at this (those dispatches are weird) I decided it was waaaay too much of a hack. Then I thought "why not go up the stack to fetch it rather than trying to mess with the nice/weird dispatch chain to send it down". I now had a third option... 3) Go up the stack to fetch the exact IP for the thread After realizing this I had my working stack crawl code only a few minutes later (I had GetCallerNameAndArgs already). Up the stack has a clear path. Down was murky and involved trampling on code I didn't want to override. The results is much cleaner than what I was doing and it worked, albeit with the as yet unfounded "crawling the stack is bad" fear still there. I should also point out that I'm not tied to SimpleXMLRPCServer, it is just a convenient example. I think any RPC protocol and dispatcher scheme would have the same problem. I'd be happy to hear about a clean stashing scheme (or any other alternative) that works for a threaded server. My biggest specific fear at the moment is that sys._frame will do funky things with multiple threads, but given that my toy example is executing in a server on its own thread and it traces perfectly I'm less worried. Come to think of it, I wonder what happens when you crawl up to and past thread creation? Hmm. From Matthew_WARREN at bnpparibas.com Fri Feb 1 08:00:30 2008 From: Matthew_WARREN at bnpparibas.com (Matthew_WARREN at bnpparibas.com) Date: Fri, 1 Feb 2008 13:00:30 +0000 Subject: How to identify which numbers in a list are within each others' range In-Reply-To: Message-ID: >> What is the best way to in python to identify the list items that >> overlap and the items that don't overlap with any other. >> >Is this usable? >Assuming you transform your 3 tuples into a list of start-end 2 tuples and sort them for lowest to highest, then >lst=[(55,58,52),(20,22,18),(17,21,13),(60,63,57)] >a=[ (l[2],l[1]) for l in lst ] >a.sort() >a=[(1,5),(4,9),(10,12),(11,15),(16,19)] >i=[ (pair,a[a.index(pair)+1]) for pair in a[:-1] if a[a.index(pair)+1][0]i >[((13, 21), (18, 22)), ((52, 58), (57, 63))] >? Ah. I guess not. That attempt doesnt catch non adjacent ranges that also overlap :/ Matt. This message and any attachments (the "message") is intended solely for the addressees and is confidential. If you receive this message in error, please delete it and immediately notify the sender. Any use not in accord with its purpose, any dissemination or disclosure, either whole or partial, is prohibited except formal approval. The internet can not guarantee the integrity of this message. BNP PARIBAS (and its subsidiaries) shall (will) not therefore be liable for the message if modified. Do not print this message unless it is necessary, consider the environment. --------------------------------------------- Ce message et toutes les pieces jointes (ci-apres le "message") sont etablis a l'intention exclusive de ses destinataires et sont confidentiels. Si vous recevez ce message par erreur, merci de le detruire et d'en avertir immediatement l'expediteur. Toute utilisation de ce message non conforme a sa destination, toute diffusion ou toute publication, totale ou partielle, est interdite, sauf autorisation expresse. L'internet ne permettant pas d'assurer l'integrite de ce message, BNP PARIBAS (et ses filiales) decline(nt) toute responsabilite au titre de ce message, dans l'hypothese ou il aurait ete modifie. N'imprimez ce message que si necessaire, pensez a l'environnement. From robin at reportlab.com Tue Feb 12 07:43:00 2008 From: robin at reportlab.com (Robin Becker) Date: Tue, 12 Feb 2008 12:43:00 +0000 Subject: 2to3.py download Message-ID: <47B19454.3020700@chamonix.reportlab.co.uk> Can anyone say how to go about obtaining 2to3.py the Python-3.0 conversion utility? There is a copy in the 3.0a2 Tools folder, but it lacks some of the sub folders. I tried various svn ls commands, but couldn't locate the actual repository. -- Robin Becker From odysseus1479-at at yahoo-dot.ca Sun Feb 3 22:21:18 2008 From: odysseus1479-at at yahoo-dot.ca (Odysseus) Date: Mon, 04 Feb 2008 03:21:18 GMT Subject: Elementary string-parsing Message-ID: I'm writing my first 'real' program, i.e. that has a purpose aside from serving as a learning exercise. I'm posting to solicit comments about my efforts at translating strings from an external source into useful data, regarding efficiency and 'pythonicity' both. My only significant programming experience is in PostScript, and I feel that I haven't yet 'found my feet' concerning the object-oriented aspects of Python, so I'd be especially interested to know where I may be neglecting to take advantage of them. My input is in the form of correlated lists of strings, which I want to merge (while ignoring some extraneous items). I populate a dictionary called "found" with these data, still in string form. It contains sub-dictionaries of various items keyed to strings extracted from the list "names"; these sub-dictionaries in turn contain the associated items I want from "cells". After loading in the strings (I have omitted the statements that pick up strings that require no further processing, some of them coming from a third list), I convert selected items in place. Here's the function I wrote: def extract_data(): i = 0 while i < len(names): name = names[i][6:] # strip off "Name: " found[name] = {'epoch1': cells[10 * i + na], 'epoch2': cells[10 * i + na + 1], 'time': cells[10 * i + na + 5], 'score1': cells[10 * i + na + 6], 'score2': cells[10 * i + na + 7]} ### Following is my first parsing step, for those data that represent real numbers. The two obstacles I'm contending with here are that the figures have commas grouping the digits in threes, and that sometimes the data are non-numeric -- I'll deal with those later. Is there a more elegant way of removing the commas than the split-and-rejoin below? ### for k in ('time', 'score1', 'score2'): v = found[name][k] if v != "---" and v != "n/a": # skip non-numeric data v = ''.join(v.split(",")) # remove commas between 000s found[name][k] = float(v) ### The next one is much messier. A couple of the strings represent times, which I think will be most useful in 'native' form, but the input is in the format "DD Mth YYYY HH:MM:SS UTC". Near the beginning of my program I have "from calendar import timegm". Before I can feed the data to this function, though, I have to convert the month abbreviation to a number. I couldn't come up with anything more elegant than look-up from a list: the relevant part of my initialization is ''' m_abbrevs = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") ''' I'm also rather unhappy with the way I kluged the seventh and eighth values in the tuple passed to timegm, the order of the date in the week and in the year respectively. (I would hate to have to calculate them.) The function doesn't seem to care what values I give it for these -- as long as I don't omit them -- so I guess they're only there for the sake of matching the output of the inverse function. Is there a version of timegm that takes a tuple of only six (or seven) elements, or any better way to handle this situation? ### for k in ('epoch1', 'epoch2'): dlist = found[name][k].split(" ") m = 0 while m < 12: if m_abbrevs[m] == dlist[1]: dlist[1] = m + 1 break m += 1 tlist = dlist[3].split(":") found[name][k] = timegm((int(dlist[2]), int(dlist[1]), int(dlist[0]), int(tlist[0]), int(tlist[1]), int(tlist[2]), -1, -1, 0)) i += 1 The function appears to be working OK as is, but I would welcome any & all suggestions for improving it or making it more idiomatic. -- Odysseus From hniksic at xemacs.org Mon Feb 4 02:49:53 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 04 Feb 2008 08:49:53 +0100 Subject: type, object hierarchy? References: <814a05b4-6f13-4c86-8c68-a30da06ca093@b2g2000hsg.googlegroups.com> Message-ID: <87ir15p3dq.fsf@mulj.homelinux.net> 7stud writes: > --output:-- > (, , ) > > The output suggests that Dog actually is a subclass of type--despite > the fact that issubclass(Dog, type) returns False. What was it in the output that gave you the impression that Dog is a subclass of type? The last entry is only for the "object" type, which you already knew Dog was a subclass of. >>> object >>> type From bj_666 at gmx.net Sat Feb 23 04:57:01 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 23 Feb 2008 09:57:01 GMT Subject: Article of interest: Python pros/cons for the enterprise References: <2f1527a7-2f66-44c7-9665-4d8ff01fa5ab@28g2000hsw.googlegroups.com> <47bd4a24$0$25225$426a74cc@news.free.fr> <036e93e6-5840-4a3c-8642-67a0a9ec44f2@i7g2000prf.googlegroups.com> <784ec210-f389-4a15-b458-961100de9103@v3g2000hsc.googlegroups.com> <9a3f9e3c-acf5-453f-a075-e0a044b21237@p73g2000hsd.googlegroups.com> <7xwsoxdzb8.fsf@ruckus.brouhaha.com> <628aluF21f45aU5@mid.uni-berlin.de> Message-ID: <62a8vdF21dimdU2@mid.uni-berlin.de> On Fri, 22 Feb 2008 10:00:16 -0800, Nicola Musatti wrote: > On Feb 22, 5:13 pm, Marc 'BlackJack' Rintsch wrote: > >> But somehow you still manage memory by writing in a style that favors >> value types. > > Certainly, but this is a natural C++ programming style, at least for > those that aren't too deeply rooted in their C heritage. Or are used to think of OOP as a graph of objects that are communicating with each other. In the value type style you are "talking" to copies of objects all the time which I find a bit confusing because *I* have to keep track of which maybe not so identical twin brother of an object I'm talking at each point. Also it seems odd to me to copy large collections around instead of passing references. Your `izip()` creates a quite small `map` -- what about big ones. With mutable objects!? I like C and until I discovered Python, I liked Java. Then I looked at C++ and find it really ugly and confusing. Even Haskell looks somewhat easier to me. Someone mentioned D -- that's a good step between C++ and Java IMHO. Garbage collection plus an easy way to declare "scoped" variables that are destroyed when the names goes out of scope. So one can leave memory management most of the time to the runtime but use RAII for files, locks and other resources. The `main()` of your C++ example looks like this in D: void main() { auto m1 = 3; auto m2 = 4; scope a = new int[0]; scope m = izip(m1, m2); foreach (int first, int second; m) { if (h(first, second).frob == 7) { a ~= [f(first) + g(second)]; } } foreach (int i; a) writef("%d\n", i); } Ciao, Marc 'BlackJack' Rintsch From micah at cowan.name Wed Feb 27 00:10:58 2008 From: micah at cowan.name (Micah Cowan) Date: Tue, 26 Feb 2008 21:10:58 -0800 Subject: network programming: how does s.accept() work? In-Reply-To: References: <6d564fca-3884-4665-8a86-f7e658217a33@e60g2000hsh.googlegroups.com> <446482ef-1fd8-41dc-a8fd-44de8b51a8e8@o10g2000hsf.googlegroups.com> <379fcee4-15e0-48c2-863b-4b7458893cbe@h25g2000hsf.googlegroups.com> <711155c0-1305-41d3-895c-af9b8fe66f21@j28g2000hsj.googlegroups.com> Message-ID: Gabriel Genellina wrote: > En Tue, 26 Feb 2008 07:53:24 -0200, 7stud > escribi?: > >> --- >> When you surf the Web, say to http://www.google.com, your Web browser >> is a client. The program you contact at Google is a server. When a >> server is run, it sets up business at a certain port, say 80 in the >> Web case. It then waits for clients to contact it. When a client does >> so, the server will usually assign a new port, say 56399, specifically >> for communication with that client, and then resume watching port 80 >> for new requests. >> --- >> http://heather.cs.ucdavis.edu/~matloff/Python/PyNet.pdf > > You should *not* trust all you find on the Net... Didn't give it a thorough read, but I did see a section about the server setting up a new socket, called a "connection socket". Which isn't incorrect, but proves Grant's point rather well, that the confusion is due to the overloaded term "socket". In that context, it's speaking quite clearly of the "Python/C/Unix" concept of a "socket", and not (as some other texts do) of the address/port combination. To reiterate for 7stud, accepting a new "connection socket" does _not_ change the address or port from the originally bound "for-listening" socket. -- Micah J. Cowan Programmer, musician, typesetting enthusiast, gamer... http://micah.cowan.name/ From codemonkey at nowhere.org Sun Feb 17 00:51:00 2008 From: codemonkey at nowhere.org (TerryP) Date: Sun, 17 Feb 2008 00:51:00 -0500 Subject: Python GUI toolkit References: Message-ID: default at defaulted.default wrote: > what would be the best python GUI toolkit, it must be cross platform. > > i have tried gtk, but it interface are real bad and its coding was > difficult so i dropped it, > > the only remaining are qt4 and wx, i would like to know if one of these or > any other toolkit is capable of creating good-looking GUI's, like in other > apps, for e.g, .net apps. > > i m a noob, and willing to learn, so difficulty is no problem I have only used the Qt bindings for GUI programming with Python or for that matter GUI programming in any language I know beyond various toolkits tutorials. I'm more accustomed code wise to the style of interface provided by the applications in /usr/bin/ on my workstation. So I like that Qt cuts the crap and provides good stuff without more nuisance then is necessary to get a functional GUI finished. -- "Earth is a great, big funhouse without the fun." -- Jeff Berner From xng at xs4all.nl Sat Feb 9 08:56:34 2008 From: xng at xs4all.nl (Martin P. Hellwig) Date: Sat, 09 Feb 2008 14:56:34 +0100 Subject: OT: Speed of light [was Re: Why not a Python compiler?] In-Reply-To: <13qkhka8rln51c5@corp.supernews.com> References: <28eead2f-a40c-414b-bd3d-a941f8a851a2@d70g2000hsb.googlegroups.com> <7da40f42-f64f-4939-a0dc-d24d1ff85f2d@v4g2000hsf.googlegroups.com> <13qjktdbe76da00@corp.supernews.com> <13qkhka8rln51c5@corp.supernews.com> Message-ID: <47adb0ca$0$31274$e4fe514c@dreader27.news.xs4all.nl> Steven D'Aprano wrote: > On Wed, 06 Feb 2008 10:14:10 -0600, Reedick, Andrew wrote: > >>>> 'c' is also the speed of light. >>> 'c' is the speed of light _in_a_vacuum_. >> True. >> >> >>>> And since nothing can travel faster than light... >>> Nothing can travel faster than the speed of light _in_a_vacuum_. There >>> are situtaitons where things can (and regularly do) travel faster than >>> light: http://en.wikipedia.org/wiki/Cherenkov_radiation >> >> Nope. It propagates, not travels, faster than light. Go ask a >> physicist to explain it. It's odd... > > Propagate, travel, what's the difference? > Unfortunately, I didn't study any of this but I sure do remember the answer one drunk physic said to me in a bar when I ask him the question: "Does light travel or propagate?" He answered: "Depends on how you see light." He must have studied philosophy too :-) -- mph From mgi820 at motorola.com Wed Feb 6 11:46:28 2008 From: mgi820 at motorola.com (Gary Duzan) Date: Wed, 6 Feb 2008 16:46:28 +0000 (UTC) Subject: Why not a Python compiler? References: <28eead2f-a40c-414b-bd3d-a941f8a851a2@d70g2000hsb.googlegroups.com> <7da40f42-f64f-4939-a0dc-d24d1ff85f2d@v4g2000hsf.googlegroups.com> <13qjktdbe76da00@corp.supernews.com> Message-ID: In article <13qjktdbe76da00 at corp.supernews.com>, Grant Edwards wrote: >On 2008-02-06, Reedick, Andrew wrote: > >> One demerit has been marked against your geek card for missing >> an obvious science pun. Additionally, your membership to the >> Star Trek Lifestyle Adventure Club has been put on >> probationary status for the next twelve parsecs. > >Ouch. Two demerits for using the distance unit "parsec" in a >context where a quantity of time was required. No demerits for Andrew; it is a Star Wars reference, which is quite on topic for this subthread. http://starwars.wikia.com/wiki/Kessel_Run Gary Duzan Motorola H&NM From nikipore at googlemail.com Wed Feb 20 14:04:26 2008 From: nikipore at googlemail.com (nikipore at googlemail.com) Date: Wed, 20 Feb 2008 11:04:26 -0800 (PST) Subject: correlation between seemingly independent instances of same class Message-ID: <56076a71-e367-4314-b53f-538ae1276783@k2g2000hse.googlegroups.com> Hello, the results of the following code boggle me. i would have expected that y.data is not affected by setting z.data. Regards Jan --code--------------------------------------------- class Test: def __init__(self, x={}): self.data = x #end def #end class Test y = Test() z = Test() print 'y.data = ',y.data print 'z.data = ',z.data z.data['B'] = 2 # this statement also sets y.data z.data= {'A': 1} # this statement doesn't print 'y.data = ',y.data print 'z.data = ',z.data --code end------------------------------------------- --output----------------------------------------------- >"C:\Program Files\Python25\pythonw" -u "thestrangething.py" y.data = {} z.data = {} y.data = {'B': 2} z.data = {'A': 1} From seberino at spawar.navy.mil Wed Feb 20 01:22:40 2008 From: seberino at spawar.navy.mil (seberino at spawar.navy.mil) Date: Tue, 19 Feb 2008 22:22:40 -0800 (PST) Subject: Why must implementing Python be hard unlike Scheme? References: Message-ID: On Feb 19, 9:49 pm, Kay Schluehr wrote: > Building a > Python VM in a high level language is certainly not harder than > creating a Scheme interpreter. Does VM = interpreter? Are you saying implementing a toy Python interpreter is not any harder than implementing a toy Scheme interpreter? I don't understand why you think that. The Python grammar is much more complicated. Python ASTs are much more complicated. Parsing Python files with the whitespace is harder. Please prove me wrong. I hope you are right. Chris From pecora at anvil.nrl.navy.mil Thu Feb 7 16:21:04 2008 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Thu, 07 Feb 2008 16:21:04 -0500 Subject: Why not a Python compiler? References: <28eead2f-a40c-414b-bd3d-a941f8a851a2@d70g2000hsb.googlegroups.com> <7da40f42-f64f-4939-a0dc-d24d1ff85f2d@v4g2000hsf.googlegroups.com> <13qjktdbe76da00@corp.supernews.com> <13qmp56btnr55a4@corp.supernews.com> <87tzkko6dv.fsf@physik.rwth-aachen.de> Message-ID: In article <87tzkko6dv.fsf at physik.rwth-aachen.de>, Torsten Bronger wrote: > > a parsec was a unit of time. > > The latter because it was corrected in the novelization. > > Tsch?, > Torsten. Sounds like one. The reverse of light year that sounds like a unit of time, but isn't. I've heard it used seriously like time in some movie. -- -- Lou Pecora From grante at visi.com Sun Feb 3 11:55:01 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 03 Feb 2008 16:55:01 -0000 Subject: Python GUI toolkit References: Message-ID: <13qbsf5aqpuulb2@corp.supernews.com> On 2008-02-03, default at defaulted.default wrote: > what i meant was, i tried gtk, didnt like it, the main reason was that it > had a very bad gui appeal for me, i did try my hand at wx , and i would have > stuck with it, Wx generally uses GTK on Unix, so if you don't like GTK, then Wx isn't really an option. Wx uses native widgets on Win32, so it'll look just as ugly as a normal Win32 app does. > but then i saw the qt4 screenshot and couple of examples of > its code and i liked it, so i was wondering, if anyone would > tell me that i should stick to wx or go forward with qt4. Stick with Wx. It uses GTK, and GTK is "native" on my system. > also, is qt4 apps better looking in both win/linux than wx > apps, coz the main thing i m looking for is visual appeal of > the gui. If what you care about is your opinion of the looks, what are you asking us for? -- Grant Edwards grante Yow! Do you like "TENDER at VITTLES"? visi.com From castironpi at gmail.com Tue Feb 19 00:08:42 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 18 Feb 2008 21:08:42 -0800 (PST) Subject: The big shots References: <89d15587-e8de-444c-b240-4a10305146e0@e23g2000prf.googlegroups.com> <7xmypx61z6.fsf@ruckus.brouhaha.com> Message-ID: On Feb 18, 10:26?pm, a... at pythoncraft.com (Aahz) wrote: > In article <7xmypx61z6.... at ruckus.brouhaha.com>, > Paul Rubin ? wrote: > > >a... at pythoncraft.com (Aahz) writes: > >>castiro... at gmail.com: > > >>>Some of the ideas that have been proposed on Python-ideas as well as > >>>Python, have received partial evaluation from the alphas. > > >> What do you mean by "alphas"? > > >Alpha test releases are the round of test distributions before the > >beta tests, which come before the release candidates which come before > >the final release. ? > > Interesting, but I would bet that castironpi actually is referring to > "alpha males" (particularly in the context of "big shots"); however, your > confusion is precisely why I called it out. ?Incoherent writing rarely > flies well in this community (which is one reason why I love Python!). > -- > Aahz (a... at pythoncraft.com) ? ? ? ? ? <*> ? ? ? ?http://www.pythoncraft.com/ > > "All problems in computer science can be solved by another level of ? ? > indirection." ?--Butler Lampson Who you callin' denigrates? Ahem. You think your ships don't sink? ;) The problem did not seem to be miscommunication, rather bias. What part of, "No one took the train before it was invented," do you not understand? No one climbed Mount Everest before it was discovered, and it wasn't the tallest mountain until then either. From gert.cuykens at gmail.com Fri Feb 15 02:07:02 2008 From: gert.cuykens at gmail.com (gert) Date: Thu, 14 Feb 2008 23:07:02 -0800 (PST) Subject: appwsgi Message-ID: can my http://appwsgi.googlecode.com/ be on the http://wsgi.org/ page somewhere please :) From enleverlesX.XmcX at XmclaveauX.com Sat Feb 2 09:45:59 2008 From: enleverlesX.XmcX at XmclaveauX.com (M¨¦ta-MCI (MVP)) Date: Sat, 2 Feb 2008 15:45:59 +0100 Subject: urllib supports javascript In-Reply-To: References: Message-ID: <47a48518$0$876$ba4acef3@news.orange.fr> Hi! "javascript support" need more details: - only the (abstract) language? - or, also, visuals aspects? On Windows, you can use,easily, the language (JScript). Example: import win32com.client js=win32com.client.Dispatch('ScriptControl') js.language='jscript' src="""function jmul2(x){ r=(x++)*2; return r; } """ js.addcode(src) print js.eval("jmul2(111);") # => 222 This simple example show how define & use a function in Javascript code. By the same way, you can mixer javascript, perlscript, vbscript, rubyscript, phpscript, etc. Now, for the visual aspect of the question, you must work differently. On way is to work in HTA (HTml Application). Inside HTA, there are a "simili-browser", able to render HTML code, and run Javascript & Pythonscript (a bit different from PythonC). Here un example:
  
MMEETTEEOO
Warning: ActiveScripting must be authorized (inside IE) Another way is to drive Interne-Explorer from Python. it's possible to call (& return) Javascript functions & code, from Python, with parameter. It's more complicated, but with more possibilities. For PLUIE, it's the way which I chose. @-salutations Michel Claveau From davidj411 at gmail.com Thu Feb 28 17:56:10 2008 From: davidj411 at gmail.com (davidj411) Date: Thu, 28 Feb 2008 14:56:10 -0800 (PST) Subject: convert string number to real number - ValueError: invalid literal for int() with base 10: '"2"' Message-ID: <3ca86e1d-a32f-48f2-bc9a-6cb792c0c631@z17g2000hsg.googlegroups.com> i am parsing a cell phone bill to get a list of all numbers and the total talktime spend on each number. i already have a unique list of the phone numbers. now i must go through the list of numbers and add up the totals for each number. on the bill, each line has a few fields,one field containing the phone number, another field containing the number of minutes on that call. the bill is comma delimited. here is the function i wrote to get one number at a time's total talktime. def getsinglenumbertalktime(number,talktime): for line in file[0:-2]: if number in line: li=line.split(',') if len(li)==6 and li[5]!="Minutes" : print "talktime type: " + str(type (talktime)) #li[5]=fpformat.fix(li[5],0) print li[5] + "li[5] type: " + str(type(li[5])) newvar = int(li[5]) print (type(newvar)) print li[5] talktime = talktime + li[5] return talktime here is the output with error that i get back. talktime type: "2"li[5] type: Traceback (most recent call last): File "", line 1, in File "c:\path\inprog\all_t_mob_nums.py", line 74, in getsinglenumbertalktime('"800-218-2644"',talktime) File "c:\path\inprog\all_t_mob_nums.py", line 66, in getsinglenumbertalktime newvar = int(li[5]) ValueError: invalid literal for int() with base 10: '"2"' here is the question: How can i convert a string number like "2" to a true number that can be added. I have tried using pfformat, float(), and int() - all with no good results. this seems like is should be simple, but it just plain isn't. I actually found a good solution. basically, take each entry and add it to a list. then iterate through the list , converting each item to int(). then add them to sum them all up. FINAL SOLUTION: def getsinglenumbertalktime(number,talktime): num_of_calls=0 num_mins=[] for line in file[0:-2]: #print "LINE: " + line #print number in line if number in line: num_of_calls += 1 #print number,num_of_calls li=line.strip("\n") #print "stripped:" + line li=li.split(',') #print "split: " + str(li) #print "len of li: " + str(len(li)) + str(num_of_calls) if len(li)==7 and li[5]!="Minutes" : #print "talktime type: " + str(type (talktime)) #print li[4] + "li[4] type: " + str(type(li[5])) #newvar = fpformat.fix(li[4],0) #print (type(newvar)) #print "len 7: " + str(type(li[6])) num_mins.append(li[6]) #talktime = talktime + int(a) if len(li)==6 and li[5]!="Minutes" : #print "talktime type: " + str(type (talktime)) #print li[5] + "li[5] type: " + str(type(li[5])) #newvar = fpformat.fix(li[4],0) #print (type(newvar)) #print "len 6: " + str(type(li[5])) num_mins.append(li[5]) #talktime = talktime + int(a) #return talktime , num_of_calls x=0 #print "this" + str(number) + str(num_mins) for a in num_mins: b=int(a) x=x+b print str(number), str(x), str(type(x)) output should look like this (parts of script are not included) 555-555-5555 replaced the innocent :P): 555-555-5555 19 555-555-5555 6 555-555-5555 3 555-555-5555 3 555-555-5555 2 555-555-5555 52 From python.list at tim.thechases.com Tue Feb 26 11:01:13 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 26 Feb 2008 10:01:13 -0600 Subject: Break lines? In-Reply-To: References: Message-ID: <47C437C9.4020004@tim.thechases.com> > I have made this string: > > TITLE = 'Efficiency of set operations: sort model, > (cphstl::set::insert(p,e)^n cphstl::set::insert(e)), integer' > > But I am not allowed to break the line like that: > > IndentationError: unexpected indent > > How do I break a line? Depends on what you want. You can embed running strings with newlines using triple-quotes (either single- or double-quotes): TITLE = """Efficiency... (cphstl:...""" Or you can use string concatenation using line-continuations: TITLE = "Efficiency..." \ "(cphstl:..." or using parens TITLE = ("Efficiency..." "(cphstl:...") I like the clean'ness of the first version, but sometimes get irked by it including my leading whitespace (there are some workarounds, but all involve more than trivial effort). I tend to use the 2nd in the case you describe, but usually using the 3rd version in all other cases where it's as a parameter to a function call or some other bracketed/braced construct. -tkc From castironpi at gmail.com Fri Feb 29 12:26:31 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 29 Feb 2008 09:26:31 -0800 (PST) Subject: Indentation and optional delimiters References: <555b548f-1296-4374-b6ce-65691d1dbb7f@s8g2000prg.googlegroups.com><13s92u3sibaus4f@corp.supernews.com><3f55d3b1-c32c-42bc-bd4b-52e2725049b0@v3g2000hsc.googlegroups.com><13scm5m9jmdns02@corp.supernews.com> <318b03dc-4cc5-49de-aeb9-e1b6e590007f@u10g2000prn.googlegroups.com> Message-ID: <6344c250-4070-4bb7-980a-9661fc789c59@d62g2000hsf.googlegroups.com> On Feb 29, 8:59?am, Steve Holden wrote: > Steve Holden wrote: > > castiro... at gmail.com wrote: > > [...] > > ?> If you want a computer language to model human thought, then is there > >> even such thing as subclassing? > > > Kindly try to limit your ramblings to answerable questions. Without keen > > insight into the function of the mind that is currently available to the > > psychological and psychiatric professions, such philosophical > > speculation is unlikely to do anyone any good, least of all you. > > ^available^unavailable^ > -- > Steve Holden ? ? ? ?+1 571 484 6266 ? +1 800 494 3119 > Holden Web LLC ? ? ? ? ? ? ?http://www.holdenweb.com/ In the neuroscience book I read (_Neuroscience_), my favorite section was entitled, "Mechanisms of Long-Term Synaptic Plasticity in the Mammalian Nervous System." Maybe reptiles do, I guess. ... and Python -is- a reptile... From brian at briansmith.org Sat Feb 16 16:47:22 2008 From: brian at briansmith.org (Brian Smith) Date: Sat, 16 Feb 2008 13:47:22 -0800 Subject: Is there a way to "link" a python program from several files? In-Reply-To: <61or3kF1ssn8aU1@mid.uni-berlin.de> References: <61or3kF1ssn8aU1@mid.uni-berlin.de> Message-ID: <002101c870e5$837da390$6501a8c0@T60> Diez B. Roggisch wrote: > Edward A. Falk schrieb: > > IOW, is there a "linker" for python? I've written a > > program comprised of about five .py files. I'd like to > > find a way to combine them into a single executable. > > Obviously, I could hand-edit them into a single > > .py file, but I'm looking for a way to keep them as > > seperate files for development but distribute the > > result as a single file. > Depending on the OS, there are several options. Ranging from > distributing an .egg (setuptools) over py2exe for windows to > py2app on OSX - and some more, e.g. cx_freeze. I would be interested in a program that can combine multiple modules into a single module, which removes all the inter-package imports and fixes other inter-module references, like Haskell All-in-One does for Haskell: http://www.cs.utah.edu/~hal/HAllInOne/index.html - Brian From lasses_weil at klapptsowieso.net Sun Feb 3 14:36:18 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Sun, 03 Feb 2008 20:36:18 +0100 Subject: Project naming suggestions? In-Reply-To: References: Message-ID: <47a617d1$0$5956$9b4e6d93@newsspool3.arcor-online.net> miller.paul.w at gmail.com wrote: > I'm considering writing a little interpreter for a python-like > language and I'm looking for name suggestions. :-) > How about "Whython"? /W From ebgssth at gmail.com Sun Feb 24 01:03:10 2008 From: ebgssth at gmail.com (js) Date: Sun, 24 Feb 2008 15:03:10 +0900 Subject: Official IRC channel for Python? In-Reply-To: References: <7xskzj7yw9.fsf@ruckus.brouhaha.com> Message-ID: No. Actually, i'm very new to IRC. On Sun, Feb 24, 2008 at 2:55 PM, Steve Holden wrote: > js wrote: > > Really? maybe I'm been blocked from it... > > thanks. > > > Currently 479 users. Have you been blocked from many channels? > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC http://www.holdenweb.com/ > > -- > > > http://mail.python.org/mailman/listinfo/python-list > From wolf_tracks at invalid.com Sun Feb 17 23:30:46 2008 From: wolf_tracks at invalid.com (W. Watson) Date: Sun, 17 Feb 2008 20:30:46 -0800 Subject: Pmw Use and Grayson's Book In-Reply-To: <74f10874-8568-4815-8eb0-a92a3301db14@34g2000hsz.googlegroups.com> References: <74f10874-8568-4815-8eb0-a92a3301db14@34g2000hsz.googlegroups.com> Message-ID: I wonder why he uses it? If I want to run his examples, where do I put the lib he includes? Same folder as the example? Mike Driscoll wrote: > On Feb 17, 9:33 pm, "W. Watson" wrote: >> I don't have Grayson's Tkinter book, but I see he uses something called Pmw. >> Why is it needed with Tkinter? >> -- >> Wayne Watson (Nevada City, CA) >> >> Web Page: > > It's not needed. It's just an extra set of widgets that are not > included in the standard set. As I recall, PMW = Python Mega-Widgets. > Check out their site: > > http://pmw.sourceforge.net/ > > You'll probably also come across Tix, another subset of widgets, which > I think is now included with Python be default from 2.4 on up. It > should be noted that PMW is not included with the standard Python > distro though. > > Mike -- Wayne Watson (Nevada City, CA) Web Page: From planders at gmail.com Tue Feb 26 11:59:37 2008 From: planders at gmail.com (Preston Landers) Date: Tue, 26 Feb 2008 08:59:37 -0800 (PST) Subject: is there enough information? References: <56783fab-c5c5-4e42-a0fb-519f75beb65a@72g2000hsu.googlegroups.com> <0f240e82-04de-497f-a9aa-07458fc97235@b1g2000hsg.googlegroups.com> <03d54be8-b1a8-455b-9e1f-c75626aedc3e@72g2000hsu.googlegroups.com> Message-ID: On Feb 26, 1:45 am, castiro... at gmail.com wrote: > Two options occurred to me, which the first showed up in the earlier > extremely skeletal and cryptic post: Perhaps you would be more likely to get the kind of help you seem to want if you refrained from posting "cryptic and skeletal" messages. The fact that many other people have pointed this out to you as of late would tend to suggest you are trolling, i.e. intentionally trying to foster miscommunication and threads that do nothing to advance anyones understanding. And regarding your other recent post about trying to find a "solution" to the "problem" of immutable types... Due to the above reasons you are unlikely to influence the design of the core language with half-baked stream of consciousness ramblings. These belong in your LiveJournal, not in c.l.python. If you have a problem you need help with, please read this entire document about 3 times before posting anything else: http://catb.org/~esr/faqs/smart-questions.html Specifically this: http://catb.org/~esr/faqs/smart-questions.html#beprecise and this: http://catb.org/~esr/faqs/smart-questions.html#goal From cokofreedom at gmail.com Wed Feb 20 06:12:39 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 20 Feb 2008 03:12:39 -0800 (PST) Subject: Double underscores -- ugly? References: <8cee096e-7f27-4162-ae09-e0fdbbc91db6@s8g2000prg.googlegroups.com> <47bb03d6$0$4281$9b4e6d93@newsspool3.arcor-online.net> <2671c516-5476-4d2b-ab33-fdf583b56316@72g2000hsu.googlegroups.com> <87zltwi8od.fsf@benfinney.id.au> <8971b484-861b-4a1b-b933-f50af7333d05@z17g2000hsg.googlegroups.com> <47bc0877$0$6144$426a74cc@news.free.fr> Message-ID: <74cc4205-ccb5-445d-9890-d5ce3b5dddfa@f47g2000hsd.googlegroups.com> So people's problem with __word__ is that it is not very readable? How so, it stands out on page, it clearly is different from other objects and doesn't abuse other symbols that generally have a meaning based on their use. I haven't seen a single alternative that really stands out as much as __word__ does. From mani.sabri at gmail.com Sun Feb 10 03:20:40 2008 From: mani.sabri at gmail.com (mani) Date: Sun, 10 Feb 2008 00:20:40 -0800 (PST) Subject: Why not a Python compiler? References: <28eead2f-a40c-414b-bd3d-a941f8a851a2@d70g2000hsb.googlegroups.com> <7da40f42-f64f-4939-a0dc-d24d1ff85f2d@v4g2000hsf.googlegroups.com> Message-ID: <05858001-97ed-4452-87c1-b1fa4cb10ea8@c23g2000hsa.googlegroups.com> On Feb 6, 2:43 am, "Luis M. Gonz?lez" wrote: > On 5 feb, 05:19, Santiago Romero wrote: > > > > > ( Surely if this question has been asked for a zillion of times... ) > > ( and sorry for my english! ) > > > I'm impressed with python. I'm very happy with the language and I > > find Python+Pygame a very powerful and productive way of writing 2D > > games. I'm not, at this moment, worried about execution speed of the > > small game I'm working on (it runs at full 60 fps even in an old AMD- > > K6 450 Laptop computer), but I continue asking me the same question: > > > Why not a Python COMPILER? > > > It would be very nice to be able to output Linux, MAC or Windows > > binaries of compiled (not bytecompiled) code. It would run faster, it > > will be smaller in size (I think) and it will be easy to distribute to > > people not having python installed. Yes, I know about py2exe, but I'm > > not sure if that's the right aproach. > > > So, what's wrong with compiling python? > > > Maybe is not possible due to nature of the language? Is just a > > decision? > > > What do you think about this? > > There are some projects aimed to speed up Python by a large margin. > Right now you can use psyco, which is considered to be feature > complete, and whose future relies on the Pypy project. > > Pypy is a very ambitious project and it aims, amongst many other > goals, to provide a fast just-in-time python implementation. > They even say that the "secret goal is being faster than c, which is > nonsense, isn?t it?" (I still didn?t get the joke though...). > > And finally, you have ShedSkin, a project developed by one lonely and > heroic coder (Mark Dufour). > Shedskin aims at being a static python compiler, which can translate a > subset of python to stand alone executables. > It also can compile extension modules for cpython. > It works by translating python to c++ and then to machine code. > The python code must be done in a static way (getting rid of dynamic > features like, for example, not asigning different types to the same > variable). > > Luis and Take a look at this page if you look for a plan to develop a fast python program, you wont regret it. http://ondrej.certik.cz/development/ Mani From nytrokiss at gmail.com Wed Feb 13 09:58:03 2008 From: nytrokiss at gmail.com (James Matthews) Date: Wed, 13 Feb 2008 15:58:03 +0100 Subject: win32com.client question In-Reply-To: References: Message-ID: <8a6b8e350802130658p7bb71365o161aa57c14735314@mail.gmail.com> What do you mean possible? On Feb 13, 2008 3:05 PM, Juan_Pablo wrote: > import win32com.client > is posible in linux ? > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://search.goldwatches.com/?Search=Movado+Watches http://www.jewelerslounge.com http://www.goldwatches.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyosohma at gmail.com Thu Feb 21 20:20:46 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 21 Feb 2008 17:20:46 -0800 (PST) Subject: OT: Ideas for a first course using Python References: Message-ID: On Feb 21, 4:48 pm, ishwar.rat... at gmail.com wrote: > Sorry to butt in but I am shopping for some ideas. > > I am interested in putting together a programming course for non- > programmers (outside the computer science domain) based on Pyhton. I > envision the course > similar to ones that used old-Basic interpreter. > > Any one out there has such a course (already designed) or has some > experience > of such a course? > > What could be a list of topics to be addressed in such a course > (domain), other > than the language syntax? > > -ishwar This guy's been doing it for a while now as a college course: http://mcsp.wartburg.edu/zelle/python/python-first.html Mike From jzgoda at o2.usun.pl Mon Feb 11 14:53:39 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Mon, 11 Feb 2008 20:53:39 +0100 Subject: Help with jabber client in wx In-Reply-To: References: Message-ID: Astan Chee pisze: > A quick note, the project started as a google talk client, but it seems > that xmpppy is flexible enough to support various other/similar XMPP > servers, but I mainly use with/in google talk > It is open source and I've included the windows executable as an > optional download. > The current problem Im having is that whenever the jabber client > disconnects or whenever a network error occurs (ISP goes down,etc), the > client does not reconnect. I've added some code to help this, but it > still doesnt reconnect properly; or rather, it doesnt detect the > disconnection properly. What am I doing wrong in the xmpppy > classes/methods? If you want to use xmppy, I'd suggest looking at Gajim team modifications to original source (http://gajim.org/). These guys did a whole lot of work making xmppy more standards compliant and fixing bugs. -- Jarek Zgoda http://zgodowie.org/ "We read Knuth so you don't have to" - Tim Peters From xng at xs4all.nl Wed Feb 13 16:15:22 2008 From: xng at xs4all.nl (Martin P. Hellwig) Date: Wed, 13 Feb 2008 22:15:22 +0100 Subject: Email Directly from python In-Reply-To: References: <47b35ab7$0$8718$e4fe514c@dreader24.news.xs4all.nl> Message-ID: <47b35e52$0$8745$e4fe514c@dreader24.news.xs4all.nl> brad wrote: > Martin P. Hellwig wrote: > >> The tricky part is how to resolve the mail server for a mail address. >> Usually you have to query the mx record of that domain. I solved that >> by looking if I can find the nslookup binary. > > The from and to are static constants... they don't change. Mail just > seems so tricky these days what with all the blacklists, greylists, > whitelists, etc. It's almost as if email is broken. Location of the > sending pc matters too. Just wondering if there is a super simple one > liner in Python (that's portable) that can do this. > Well the problem is that you can't control whether the to address won't be handled with a different mail server in the future. Whether the receiving party marks your mail as spam or not is actually their problem. If you act according to the RFC's it should be delivered. Of course it helps if you don't make the content be spam ;-) -- mph From roger.dahlstrom at gmail.com Mon Feb 4 14:25:00 2008 From: roger.dahlstrom at gmail.com (rdahlstrom) Date: Mon, 4 Feb 2008 11:25:00 -0800 (PST) Subject: Windows - remote system window text References: <3b29a22b-55cd-4430-9a47-cba4941e9b8c@h11g2000prf.googlegroups.com> <9d71dbbb-240a-44c5-9e3f-ef223133152e@z17g2000hsg.googlegroups.com> Message-ID: <11db701c-d1f2-4970-8f83-df214bdca7c5@b2g2000hsg.googlegroups.com> On Feb 4, 2:17 pm, "m... at infoserv.dk" wrote: > Well, i guess you will need a process on each machine you need to > monitor, and then you do have a client server setup. > > This can be easily accomplished with fx Pyro (http:// > pyro.sourceforge.net/) for communication, and the Win32 Python library > (https://sourceforge.net/projects/pywin32/) for creating a service. Crap, that's what I didn't want to do. I am slowly coming to the realization that I'm going to have to, but I really didn't want to do that. That brings up a whole host of other things that I would then have to do - remote installation, etc. I guess I could do it, but I'd really rather not. From bellman at lysator.liu.se Tue Feb 5 13:14:28 2008 From: bellman at lysator.liu.se (Thomas Bellman) Date: Tue, 5 Feb 2008 18:14:28 +0000 (UTC) Subject: polling for output from a subprocess module References: <48dec8a9-c2da-492c-a639-097fe25fe73c@s8g2000prg.googlegroups.com> Message-ID: Christian Heimes writes: > Thomas Bellman wrote: >> The readlines() method will read until it reaches end of file (or >> an error occurs), not just what is available at the moment. You >> can see that for your self by running: > Bad idea ;) Why is it a bad idea to see how the readlines() method behaves? > readlines() on a subprocess Popen instance will block when you PIPE more > than one stream and the buffer of the other stream is full. > You can find some insight at http://bugs.python.org/issue1606. I > discussed the matter with Guido a while ago. Umm... Yes, you are correct that the code in the original post also has a deadlock problem. I missed that. But saying that it is the readline() method that is blocking is a bit misleading, IMHO. Both processes will be blocking, in a deadly embrace. It's a problem that has been known since the concept of inter- process communication was invented, and isn't specific to the readlines() method in Python. But the OP *also* has the problem that I described in my reply. Even if he only PIPE:d one of the output streams from his subprocess, he would only receive its output when the subprocess finished (if it ever does), not as it is produced. (To those that don't understand why the OP's code risks a deadly embrace: if a process (A) writes significant amounts of data to both its standard output and standard error, but the process that holds the other end of those streams (process B) only reads data from one of those streams, process A will after a while fill the operating system's buffers for the other stream. When that happens, the OS will block process A from running until process B reads data from that stream too, freeing up buffer space. If process B never does that, then process A will never run again. The OP must therefore do a select() on both the standard output and standard error of his subprocess, and use os.read() to retrieve the output from both streams to free up buffer space in the pipes.) -- Thomas Bellman, Lysator Computer Club, Link?ping University, Sweden "We don't understand the software, and ! bellman @ lysator.liu.se sometimes we don't understand the hardware, ! but we can *see* the blinking lights!" ! Make Love -- Nicht Wahr! From cyberco at gmail.com Fri Feb 22 18:31:10 2008 From: cyberco at gmail.com (Berco Beute) Date: Fri, 22 Feb 2008 15:31:10 -0800 (PST) Subject: Web Development Project References: Message-ID: <4ce72423-4c0f-4cce-926b-efa76d735497@i7g2000prf.googlegroups.com> linux lighttpd fastcgi django sqlite3 ...rocking combo :) From rconradharris at gmail.com Thu Feb 14 13:42:38 2008 From: rconradharris at gmail.com (Rick Harris) Date: Thu, 14 Feb 2008 10:42:38 -0800 (PST) Subject: Copying weakrefs References: <7eac1891-66b2-4716-86f1-f85292b1c822@e25g2000prg.googlegroups.com> Message-ID: On Feb 14, 12:31 pm, Rick Harris wrote: > I am working with an object, Context, that maintains an identity map > by using the weakref.WeakValueDictionary. I would like to clone this > Context object (and objects that may have a Context object) using > copy.deepcopy(). When I try to do this, the deep copy operation > recurses down to the WeakValueDictionary, down to the KeyedRef > subclass of ref, and then fails. It seems that copy.copy() and > copy.deepcopy() operations on weakrefs just won't work. > > The failure can be replicated with this (much simpler) scenario: > > >>> import weakref, copy > >>> class Test(object): pass > >>> t = Test() > >>> wr = weakref.ref(t) > >>> wr_new = copy.copy(wr) # Fails, not enough args to __new__ > > Anybody out there have some insight into this? > > Thanks > Rick Update: I was able to monkey-patch the copy module's dispatch tables to (seemingly) fix this. The code is: >>> copy._copy_dispatch[weakref.ref] = copy._copy_immutable >>> copy._deepcopy_dispatch[weakref.KeyedRef] = copy._deepcopy_atomic Could somebody more familiar with Python internals look into whether this patch is a) correct and b) whether this should be added to copy module? Thanks, Rick From nick at stinemates.org Mon Feb 18 22:19:44 2008 From: nick at stinemates.org (Nick Stinemates) Date: Mon, 18 Feb 2008 19:19:44 -0800 Subject: name of client module In-Reply-To: References: <2KCdnWJQeaBuuCfanZ2dnUVZ_sednZ2d@comcast.com> Message-ID: <47BA4AD0.2030407@stinemates.org> Jeff Schwab wrote: > Nick Stinemates wrote: > >>> I'm not saying I don't want to do that. I'm saying that, in addition to >>> what you've written, I want foo to know it's being imported, and by whom. >>> > > Please don't snip so much. > > >> You're still not explaining a real example of what this could be used for. >> > > Why would you say something like that? I told you *exactly* what I > wanted to use it for. See Berwyn's post on the recent thread "Double > underscores -- ugly?" He suggests that a suitable replacement for "if > __name__ == '__main__'" might be "if sys.main()". I was looking for a > way to implement that kind of function. Just like I told you when you > asked me. You snipped it, along with most of the post. > > >> Oh well, here's an example of an implementation of what you want to do. >> > > Thanks. > Ah, I snipped because I was only replying to that specific part and thought there was an archive of the rest. If that is unconventional I'll stop. I suppose I did get a bit carried away. It seems people always want to know 'who is calling my object' but I think writing a design around that is: a) Really hard to follow, much like GoTo statements b) Poorly thought out and, probably much more importantly c) Grouping code together like that really limits what you can do with it.. I'm sorry if I offended. -- ================== Nick Stinemates (nick at stinemates.org) http://nick.stinemates.org AIM: Nick Stinemates MSN: nickstinemates at hotmail.com Yahoo: nickstinemates at yahoo.com ================== From john106henry at hotmail.com Thu Feb 21 16:53:53 2008 From: john106henry at hotmail.com (John Henry) Date: Thu, 21 Feb 2008 13:53:53 -0800 (PST) Subject: Return value of an assignment statement? References: <6d945394-739e-4c47-ad71-faaab8f9d566@34g2000hsz.googlegroups.com> <835a4fc1-f62a-4141-bca4-4e4f52519466@s37g2000prg.googlegroups.com> Message-ID: On Feb 21, 1:48 pm, John Henry wrote: > On Feb 21, 1:43 pm, mrstephengross wrote: > > > > > Hi all. In C, an assignment statement returns the value assigned. For > > instance: > > > int x > > int y = (x = 3) > > > In the above example, (x=3) returns 3, which is assigned to y. > > > In python, as far as I can tell, assignment statements don't return > > anything: > > > y = (x = 3) > > > The above example generates a SyntaxError. > > > Is this correct? I just want to make sure I've understood the > > semantics. > > > Thanks, > > --Steve > > That's true, and I am happy that they decided to make that a syntax > error. BTW: The less obvious issues when coming from the C world are Python syntax like these: y = x = 3 a = 4 y = x = a print x,y a = 5 print x,y From bearophileHUGS at lycos.com Thu Feb 14 06:26:24 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 14 Feb 2008 03:26:24 -0800 (PST) Subject: Regular Expression for Prime Numbers (or How I came to fail at them, and love the bomb) References: <85ca4615-c51f-4aab-b400-f3f80056faec@l32g2000hse.googlegroups.com> <81744abc-7542-4196-bbbf-9a0248805311@d21g2000prf.googlegroups.com> Message-ID: <454b9118-1639-4d9c-92f8-24f4f897755b@e10g2000prf.googlegroups.com> cokofree: > Sadly that is pretty slow though... It's quadratic, and it's not even short, you can do (quadratic still): print [x for x in range(2, 100) if all(x%i for i in range(2, x))] In D you can write similar code. Bye, bearophile From dhwild at talktalk.net Wed Feb 13 14:16:29 2008 From: dhwild at talktalk.net (David H Wild) Date: Wed, 13 Feb 2008 19:16:29 +0000 (GMT) Subject: OT: Speed of light References: <6f-dnfwZwvz6Ui3anZ2dnUVZ_oOnnZ2d@speakeasy.net> <13r2p6aivk1no9a@corp.supernews.com> <880dece00802121311n77f73515ve7db8a931825d958@mail.gmail.com> <87abm4g1tw.fsf@mulj.homelinux.net> <5LednYnShMTspS7anZ2dnUVZ_ternZ2d@comcast.com> Message-ID: <47b34916$0$1342$834e42db@reader.greatnowhere.com> In article <5LednYnShMTspS7anZ2dnUVZ_ternZ2d at comcast.com>, Jeff Schwab wrote: > We (Americans) all measure our weight in pounds. People talk about how > much less they would weigh on the moon, in pounds, or even near the > equator (where the Earth's radius is slightly higher). Their weight on the moon would be exactly the same as on earth if they used a balance with weights on the other side of the fulcrum. -- David Wild using RISC OS on broadband www.davidhwild.me.uk From noname9968 at gmail.com Mon Feb 18 11:49:02 2008 From: noname9968 at gmail.com (Alex) Date: Mon, 18 Feb 2008 19:49:02 +0300 Subject: How to get current module object In-Reply-To: References: <47B87C28.3030302@gmail.com> Message-ID: <47B9B6FE.50508@gmail.com> Gabriel Genellina wrote: > En Sun, 17 Feb 2008 16:25:44 -0200, Alex escribi?: > >> Can I get reference to module object of current module (from which the >> code is currently executed)? I know __import__('filename') should >> probably do that, but the call contains redundant information (filename, >> which needs to be updated), and it'll perform unnecessary search in >> loaded modules list. >> >> It shouldn't be a real problem (filename can probably be extracted from >> the traceback anyway), but I wonder if there is more direct and less >> verbose way. >> > sys.modules[__name__] > That's what I've been searching for, thanks. By the way, I know it might be trivial question... but function and class namespaces have __name__ attribute too. Why is global one always returned? > Why do you want to get the module object? globals() returns the module > namespace, its __dict__, perhaps its only useful attribute... To pass it as a parameter to a function (in another module), so it can work with several modules ("plugins" for main program) in a similar manner. From terry at jon.es Sun Feb 17 11:41:19 2008 From: terry at jon.es (Terry Jones) Date: Sun, 17 Feb 2008 17:41:19 +0100 Subject: flattening a dict In-Reply-To: Your message at 04:51:37 on Sunday, 17 February 2008 References: <36e90615-f6fe-4b39-b8a8-eb4d28583a58@j28g2000hsj.googlegroups.com> <09c2d0ff-f5f5-4879-9808-4768f60d6a51@28g2000hsw.googlegroups.com> <28cc2bbf-bb1d-4376-862b-b31fe140e193@v3g2000hsc.googlegroups.com> Message-ID: <18360.25519.160393.223279@jon.es> >>>>> "Arnaud" == Arnaud Delobelle writes: Arnaud> BTW, I keep using the idiom itertools.chain(*iterable). I guess Arnaud> that during function calls *iterable gets expanded to a tuple. Arnaud> Wouldn't it be nice to have an equivalent one-argument function Arnaud> that takes an iterable of iterables and return the 'flattened' Arnaud> iterable? This reminds me of a function I wrote a while back that iterates over all its arguments, even calling passed functions and iterating over their results. I knew *even less* about Python then than I do now; please set flamethrowers to "Constructive Criticism". http://www.fluidinfo.com/terry/2007/05/07/iteranything/ Terry From tmp1 at viltersten.com Thu Feb 28 23:38:04 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Fri, 29 Feb 2008 05:38:04 +0100 Subject: SV: Running test01.py under Windows (basic level) In-Reply-To: References: <62os33F2352veU1@mid.individual.net> Message-ID: <62pfi6F244l0bU1@mid.individual.net> >> def bloppA (): >> print "a very advanced piece of code" > > go to File -> Open, open your saved file, > and use the Run menu (or press F5). When i try that i get this. >>> ====== RESTART ======= >>> And nothing more. Do i use wrong "print"?! -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From zentraders at gmail.com Fri Feb 15 13:55:47 2008 From: zentraders at gmail.com (Zentrader) Date: Fri, 15 Feb 2008 10:55:47 -0800 (PST) Subject: Floating point bug? References: <6eba298e-6888-462a-afa7-54fae02c3dce@y5g2000hsf.googlegroups.com> <61ibo1F1uqso2U1@mid.uni-berlin.de> <188be6e9-bc05-4a72-924b-1de184980002@n58g2000hsf.googlegroups.com> Message-ID: <9b166b3d-89df-4f26-956a-abbd391167e7@i12g2000prf.googlegroups.com> I disagree with this statement But that doesn't change the fact that it will expose the same rounding-errors as floats do - just for different numbers. The example used has no rounding errors. For anything less that 28 significant digits it rounds to 1.0. With floats 1.0/3 yields 0.33333333333333331<-- on my machine. Also you can compare two decimal.Decimal() objects for equality. With floats you have to test for a difference less than some small value. BTW, a college professor who also wrote code for a living made this offhand remark "In general it is best to multiply first and then divide." Good general advice. From ptmcg at austin.rr.com Fri Feb 22 12:31:53 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 22 Feb 2008 09:31:53 -0800 (PST) Subject: Simple - looking for a way to do an element exists check.. References: Message-ID: <4f394676-0957-4d68-b9e1-6a2d8ff22e4a@d21g2000prf.googlegroups.com> On Feb 22, 11:20?am, rh0dium wrote: > Hi all, > > I have a simple list to which I want to append another tuple if > element 0 is not found anywhere in the list. > > element = ?('/smsc/chp/aztec/padlib/5VT.Cat', > ? '/smsc/chp/aztec/padlib', > ? '5VT.Cat', (33060)) > > element1 = ?('/smsc/chp/aztec/padlib/5VT.Cat2', > ? '/smsc/chp/aztec/padlib', > ? '5VT.Cat2', (33060)) > > a = ?[ ('/smsc/chp/aztec/padlib/5VT.Cat', > ? '/smsc/chp/aztec/padlib', > ? '5VT.Cat', (33060)), > ?('/smsc/chp/aztec/padlib/padlib.TopCat%', > ? '/smsc/chp/aztec/padlib', > ? 'padlib.TopCat%', (33204)), > ?('/smsc/chp/aztec/padlib/Regulators.Cat%', > ? '/smsc/chp/aztec/padlib', > ? 'Regulators.Cat%', (33204))] > > So my code would look something like this. > > found = False > for item in a: > ? if item[0] == element[0] > ? ? found = True > ? ? break > if not found: > ? a.append(element) > > But this is just ugly - Is there a simpler way to interate over all > items in a without using a found flag? > > Thanks Well, that's what I get for typing before thinking... If the remaining items in each element tuple are the same for any given element[0], then just use a set. aset = set(a) for element in list_of_new_element_tuples: aset.add(element) -- Paul From siona at chiark.greenend.org.uk Tue Feb 19 11:42:58 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 19 Feb 2008 16:42:58 +0000 (GMT) Subject: Linux/Python Issues References: <15a5dab0-02b7-49bb-9a3a-7883c6bd424b@i29g2000prf.googlegroups.com> Message-ID: wrote: >CNR, which is now free, is absolutely marvelous when it's got what you >need. If Python2.5 were in the warehouse, I'd have clicked, gone to >make a cup of coffee and the appropriate icon would be on my desktop >when I came back. If I were Python.org I'd not consider anything ready >for release until it was in the warehouse. Er, so how is it supposed to get into the warehouse if it's not first released from python.org ? -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From castironpi at gmail.com Sat Feb 23 16:39:17 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 23 Feb 2008 13:39:17 -0800 (PST) Subject: @synchronized dect'r &c. References: <0f6f2afe-baf1-4e7f-b8fb-859147636648@m23g2000hsc.googlegroups.com> Message-ID: <3b41fefe-899c-435f-8bca-c282e923390b@b29g2000hsa.googlegroups.com> Corrections. Typographical error in the implementation of #1. def synchronized( func ): def presynch( *ar, **kwar ): with _synchlock: lock= _synchhash.setdefault( func, allocate_lock() ) with lock: return func( *ar, **kwar ) return presynch On footnote #4, one might need a vector of jump addresses, one for each context in which the word might be modified. Yes, this involves a miniature "many small" design in actual hardware memory, and definitely opens some doors to faster processing. As such, it may not be the best "first" structural element in paralell off-loading, but it's a good one. And yes, it's specialty RAM, for which RAM may not even be the right place. If a few KB of it is enough, just bump it up next to the cache, which may make for shorter cycles on the jump-back later. You probably don't want to be setting the instruction pointer from a KB's worth of addresses, so there's probably an extra cycle involved in setting the jump register, halting the IP, and signalling a jump. Interrupts may be suited too. Does the OS need to provide an API before a compiler can make use of it? On #4, the signatures func( self, locks ) vs. func( locks, self ) is open: just if you sometimes want locks to be the second parameter, and other times the first, as for non-class-member functions, there will be two methods, or a parameter to signal the difference. From deets at nospam.web.de Sat Feb 16 05:55:04 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 16 Feb 2008 11:55:04 +0100 Subject: Where can I get the module MyUtils? In-Reply-To: <4aed89a3-95d4-4ee8-96c2-74556abe17ef@s37g2000prg.googlegroups.com> References: <4aed89a3-95d4-4ee8-96c2-74556abe17ef@s37g2000prg.googlegroups.com> Message-ID: <61ntodF20i8ouU1@mid.uni-berlin.de> Python_Doctor schrieb: > I inherited a piece of python code which imports "MyUtils" i.e. it has > a line: > > import MyUtils > > When I execute the code I get: > > ImportError: No module named MyUtils > > I assume the code is looking for another module called MyUtils.py. Is > this a standard Python module? Where can I download this module from? How large are the chances that something called "MyUtils" is a standard-module? And if it were - you wouldn't miss it, wouldn't you? I suggest you ask the one you inherited the code from - it's mosp probably his/hers. Diez From bbxx789_05ss at yahoo.com Sun Feb 17 20:21:16 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Sun, 17 Feb 2008 17:21:16 -0800 (PST) Subject: Tkinter Confusion References: <13044921-c8bc-4101-a98a-9fb0c0dadad9@n77g2000hse.googlegroups.com> Message-ID: <49315903-ca49-4bb6-ae68-658bc3fb6355@n58g2000hsf.googlegroups.com> On Feb 17, 12:36?pm, MartinRineh... at gmail.com wrote: > Everything I've read about Tkinter says you create your window and > then call its mainloop() method. But that's not really true. This is > enough to launch a default window from the console: > > >>>from Tkinter import * > >>>foo = Tk() > You shouldn't care what happens in an interactive python session. In fact, you can take years off your life trying to figure out why the output of an interactive session is different from the output of a python program. Here is how to create a basic window with one widget: import Tkinter as tk root = tk.Tk() label = tk.Label(root, text='hello world') label.pack() #makes widget visible root.mainloop() Adding in some more details: import Tkinter as tk root = tk.Tk() root.geometry('600x400') root.config(background='red') label = tk.Label(root, text='hello world', background='gray') label.pack() #makes widget visible root.mainloop() > Google's great, but it has no truth meter. Do I inherit from Frame? A frame is used to group widgets. You can have multiple frames each containing a group of widgets. That will allow you to place the group as a whole at a specific location in the window. Here's how to use frames to organize widgets: import Tkinter as tk root = tk.Tk() root.geometry('600x400') root.config(background='red') frame1 = tk.Frame(root) label1 = tk.Label(frame1, text='hello world', background='gray') label2 = tk.Label(frame1, text='goodbye', background='gray') label1.pack() #makes label visible label2.pack() #makes label visible frame1.pack(side=tk.BOTTOM) #makes frame visible frame2 = tk.Frame(root) label3 = tk.Label(frame2, text='yes', background='yellow') label4 = tk.Label(frame2, text='no', background='yellow') label5 = tk.Label(frame2, text='maybe', background='yellow') label3.pack() label4.pack() label5.pack() frame2.pack(side=tk.TOP) frame3 = tk.Frame(root) label6 = tk.Label(frame3, text='a', background='blue') label7 = tk.Label(frame3, text='b', background='blue') label8 = tk.Label(frame3, text='c', background='blue') label6.pack() label7.pack() label8.pack() frame3.pack(side=tk.LEFT) root.mainloop() > Do I use > Tk() or toplevel()? (Support for both and if a cogent explanation of > the differences exists, I didn't find it.) > Tk() for you first window; Toplevel() for any additional windows you want to open: import Tkinter as tk root = tk.Tk() root.geometry('300x200+50+50') #+x+y positions window root.config(background='red') label = tk.Label(root, text='hello world', background='gray') label.pack() window2 = tk.Toplevel() window2.geometry('300x200+400+50') root.mainloop() From spradml at gmail.com Sun Feb 17 04:59:15 2008 From: spradml at gmail.com (Pradnyesh Sawant) Date: Sun, 17 Feb 2008 15:29:15 +0530 Subject: xmltramp with python2.(4-5) In-Reply-To: <41355cfe-226b-4cf9-bb11-bf3479144d31@e10g2000prf.googlegroups.com> References: <41355cfe-226b-4cf9-bb11-bf3479144d31@e10g2000prf.googlegroups.com> Message-ID: <20080217095915.GC24617@debian> On 22:51, 16Feb2008, John Machin wrote: > On Feb 17, 5:40 pm, Pradnyesh Sawant wrote: > > fire up python2.4 interactive prompt > do this: > import sys; sys.path > import xmltramp; xmltramp.__file__ > > then fire up python2.5 interactive prompt > do this: > import sys; sys.path Hey, thanks a lot for that reply. it made me realise that xmltramp was something that is there in '/usr/lib/python2.4/site-packages/xmltramp.pyc' (a site-package for 2.4), and is hence not available for 2.5 it also showed me that I had _not_ installed it using apt for debian. unforutnately I dunno where I had got it from, and searching online didn't give me the result I wanted. anyways, thanks for leading me in the proper direction :) > > If that doesn't give you enough to nut out where xmltramp is and hence > why it's on one sys.path and not on the other, come back with the full > output from the above (including the info that python prints that > will tell us helpful things like what platform you are on) > > -- > http://mail.python.org/mailman/listinfo/python-list -- warm regards, Pradnyesh Sawant -- We are not just our behaviour. We are the person managing our behaviour. --The One Minute Manager -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From dblubaugh at belcan.com Fri Feb 1 12:52:10 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Fri, 1 Feb 2008 12:52:10 -0500 Subject: MyHDL project for FPGA development! In-Reply-To: <86380fd30802010813r7f46cd3tfc01995750cced21@mail.gmail.com> References: <27CC3060AF71DA40A5DC85F7D5B70F380239F9AE@AWMAIL04.belcan.com> <86380fd30802010813r7f46cd3tfc01995750cced21@mail.gmail.com> Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F380244BFA1@AWMAIL04.belcan.com> Dan, Thank you very much for your reply. My Master's thesis is for Wright State University and is of the following nature: I am currently engaged with a Masters project, that utilizes a linear array of isotropic sensors, or in my case electromagnetic antennas. I am trying to develop a specialized Multidimensional FFT processor, that can determine the angle of arrival and frequency content of a perceived target with respect to the position of the linear array. I should further state that this Multidimensional FFT processor is currently of only two dimensions. Therefore, the MDFFT will only have a result of frequency value versus angle of arrival of the target with respect to the position of the linear array. There is a great deal of mathematics that are involved (SciPy), especially considering that in order to model the two-dimensional signal of the linear sensor array, I have to utilize concepts borrowed from differential geometry. This is why I will need to utilize a toolset like SciPy with python. I would still like to include the ImpulseC environment, since the environment does provide an interesting connection between FPGA hardware and software running on embedded processors ,such as the Power PC on Xilinx FPGAS. I believe that a marriage between Python, ImpulseC, MyHDL, SciPy, Gene Expression Programming, and GNU Plot will develop into a very interesting and powerful algorithm development environment for FPGAS. I will also need a way to develop floating-point hardware, since I will need to have the dynamic range of floating-point in order to determine the angle of arrival of targets placed many miles away from the linear sensor array. This is why Impulse C should still be considered, since they provide the ability of generating efficient floating-point hardware. I have to go now, since I have to report for my employment duties. In conclusion, I would very much to continue development for a Python, Scipy, MyHDL combined. If there are any more questions, Dan, please contact me as soon as possible. Respectfully, David ________________________________ From: Dan Fabrizio [mailto:dfabrizio51 at gmail.com] Sent: Friday, February 01, 2008 11:14 AM To: Blubaugh, David A. Subject: Re: MyHDL project !!!!! David, Let's start by discussing your masters thesis subject in more detail. We can take a project from conception to hardware using MyHDL, NumPy and SciPy. Maybe you could use this project as a proof for your thesis showing this methodology warrants consideration compared other ASIC/FPGA flows. Let's discuss some of your ideas and decide how to proceed. Dan On Feb 1, 2008 10:43 AM, Blubaugh, David A. wrote: Dan, I would be honored to start a project such as that in mind. How do we begin ?????? David Blubaugh -----Original Message----- From: chewie54 [mailto:dfabrizio51 at gmail.com] Sent: Thursday, January 31, 2008 9:34 PM To: python-list at python.org Subject: Re: Will Python on day replaceMATLAB????????????????????????????????????????????????????? > I have been evaluating the python environment ever more closer. I > believe I can interface python with a development environment known as > the ImpulseC environment. The ImpulseC environment develops C to VHDL > for FPGA development. I would especially love to interface Python > with ImpulseC and the graphing capabilities of GNU Plot and SciPy in > order to recreate a VHDL development environment that will be just as > capable as a $50,000 dollar Matlab to VHDL toolbox. This is also a > part of my Masters thesis. Is anyone willing to help in this endeavor????? > > David Blubaugh > Why not use MyHDL which is written in Python and translates to Verilog. I assume ImpulseC is a commercial product and costs a log. MyHDL is free. If you have any interests in combining MyHDL with SciPy and NumPy I would be interested in getting involved. Dan Fabrizio This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Fri Feb 8 19:23:55 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 08 Feb 2008 19:23:55 -0500 Subject: Why not a Python compiler? In-Reply-To: <13qp5a02t36def9@corp.supernews.com> References: <28eead2f-a40c-414b-bd3d-a941f8a851a2@d70g2000hsb.googlegroups.com> <81339c25-f9b6-47a1-941e-8ae39c35773c@e6g2000prf.googlegroups.com> <98a1bc2d-290b-4b6d-8a3d-eda7666d2b8b@l1g2000hsa.googlegroups.com> <13qmtu5j1b1p6a2@corp.supernews.com> <8763x0fix1.fsf@mulj.homelinux.net> <13qp5a02t36def9@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2008-02-08, Arnaud Delobelle wrote: > >>> the compiler could do little else except translate it to something >>> like: >>> >>> (python:add a b) >> [snip more interesting considerations about compiling python] >> >> Please get back on topic. This discussion is about parsecs and >> wookies now. > > What's a "wookie" a unit of? > A wookie is someone who's onwy just joined a team and hasn't pwayed vewy much. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From sean at chittenden.org Wed Feb 27 14:42:59 2008 From: sean at chittenden.org (Sean Chittenden) Date: Wed, 27 Feb 2008 11:42:59 -0800 Subject: refreshing the cache time of a key In-Reply-To: <910313af0802270417s758f7962h656310da1b11e62@mail.gmail.com> References: <910313af0802270417s758f7962h656310da1b11e62@mail.gmail.com> Message-ID: <1F569950-0E61-4F7F-AB6C-42D819B9CAC9@chittenden.org> > is it possible to refresh the cache time of a key with out having > to retrieving the cached data and storing it back in memcache .. for > example if a data is cached for > 1 hour and at the 50th minute from the time this data has been > cached i want to store it in the cache for 1 more hour ..is > there a function to refresh the cache time by knowing the key of > data with out having to do get and set > i.e > data=mc.get(key) > mc.set(key,data,3600) # 1 more hour It's not possible with the current code base. I posted a patch a few years back that did this.... here we go: http://lists.danga.com/pipermail/memcached/2004-November/000880.html It should be easy to apply the patch by hand if it fails to apply cleanly out of the gate. FWIW, I find this functionality invaluable. See the post for details. -sc -- Sean Chittenden sean at chittenden.org http://sean.chittenden.org/ From AWasilenko at gmail.com Sat Feb 16 11:35:38 2008 From: AWasilenko at gmail.com (Adam W.) Date: Sat, 16 Feb 2008 08:35:38 -0800 (PST) Subject: Easy PIL question Message-ID: <6cd3f2f9-a65f-408f-a40d-6ef4036a2b41@q70g2000hsb.googlegroups.com> I know there is an easy way to do this, but I can't figure it out, how do I get the color of a pixel? I used the ImageGrab method and I want to get the color of a specific pixel in that image. If you know how to make it only grab that pixel, that would also be helpful. Basically I'm trying to make a: if pixel == color: do_this() else: pass And have it do this as fast as my pc can handle (that is why only grabbing 1px would be helpful) From lizhongan at gmail.com Fri Feb 22 02:22:20 2008 From: lizhongan at gmail.com (zaley) Date: Thu, 21 Feb 2008 23:22:20 -0800 (PST) Subject: Is there a open souce IDE writen by C( C++) or partly writen by C( C++)? References: <42a838b9-2023-4cbf-bc53-e7ac5f4accbc@i7g2000prf.googlegroups.com> <47BE6D27.7000305@behnel.de> Message-ID: My project need a simple scripts debugger . I hope I can find something instructive Stefan Behnel ??? > zaley wrote: > > Is there a open souce IDE writen by C( C++) or partly writen by C( C+ > > +)? > > Tons of them. What do you want to do with it? > > Stefan From gagsl-py2 at yahoo.com.ar Fri Feb 15 18:28:04 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 15 Feb 2008 21:28:04 -0200 Subject: Assignment saves time? References: <87bq6iphua.fsf@mulj.homelinux.net> <45fe7ed2-0cd6-4287-a81c-63749041e8d0@e23g2000prf.googlegroups.com> <8e3ae780-75aa-4ba0-a19a-ddc91664b888@o77g2000hsf.googlegroups.com> Message-ID: En Fri, 15 Feb 2008 18:51:19 -0200, escribi?: > I ran it in an interactive python shell, which might have made a > difference. > > import timeit > time1=timeit.Timer('s=len(li); s==1000', 'li=range(1000)') > time2=timeit.Timer('len(li)==1000', 'li=range(1000)') > store=min(time1.repeat(5)) > call=min(time2.repeat(5)) > store=min(min(time1.repeat(5)),store) > call=min(min(time2.repeat(5)),call) > store > 0.25531911849975586 > call > 0.25700902938842773 > > The difference is small enough to be insignificant, but I am curious > how it's possible and why it happened. It's more likely a reflection > of how I timed it than anything else, isn't it? Yes, I think it's an artifact of how you measured it. I've tried this: import timeit time1=timeit.Timer('s=len(li); s==1000', 'li=range(1000)') r1 = time1.repeat(5) print 'store', min(r1), r1 time2=timeit.Timer('len(li)==1000', 'li=range(1000)') r2 = time2.repeat(5) print 'call', min(r2), r2 and got the expected results: store 0.336916842783 [0.33712636661922118, 0.34131209413486907, 0.33691684278309109, 0.33726828409755982, 0.34154312908484186] call 0.296055783626 [0.29648125669603265, 0.29605578362613105, 0 .29716346630647195, 0.29883546651878934, 0.29798368228364236] -- Gabriel Genellina From grante at visi.com Tue Feb 26 14:25:02 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 26 Feb 2008 19:25:02 -0000 Subject: How about adding rational fraction to Python? References: <1bc9bba7-dc7f-4cfe-8e1c-fa5901c9f556@n77g2000hse.googlegroups.com> <97f30679-483d-4751-9a6e-0858b36eb426@d4g2000prg.googlegroups.com> <649ac8a9-ae09-4e9b-85c2-f37043af21fd@28g2000hsw.googlegroups.com> <0d1955fc-762c-44e1-a5d8-372c71458455@p25g2000hsf.googlegroups.com> <36204e6f-0d82-449b-8ca5-c819ace9a55a@p73g2000hsd.googlegroups.com> <9503b14b-7bd5-42b4-b3f7-673d0ebd7feb@c33g2000hsd.googlegroups.com> <602ac27c-4aaa-49b2-bee2-1e0e0c705983@i7g2000prf.googlegroups.com> <13s8j1tglqpth80@corp.supernews.com> <6aWdnZtVGbEd01nanZ2dnUVZ_q_inZ2d@comcast.com> Message-ID: <13s8pse1m27od78@corp.supernews.com> On 2008-02-26, Jeff Schwab wrote: > Grant Edwards wrote: > >> I guess it must depend on where you went to shool. > > Temple Israel. You? Good one. :) -- Grant Edwards grante Yow! Do you think the at "Monkees" should get gas on visi.com odd or even days? From krishnakirti at gmail.com Tue Feb 26 16:23:44 2008 From: krishnakirti at gmail.com (Krishna Kirti Das) Date: Tue, 26 Feb 2008 13:23:44 -0800 (PST) Subject: Windows System Administration: State of the Art on Python? Message-ID: <590cef15-941a-4f65-8acb-d3023a2dc08a@d21g2000prf.googlegroups.com> I am a long-time user of Perl who comes to you in peace and is evaluating different scripting languages for use as a scripting platform for system administrators on the Windows platform. Perl already has many modules that allow sys admins and devolpers to do lots of things with the Windows OS, and I'm wondering what the state of the art is with Python and being able to control and administer a windows environment. In this regard, how does Python stand up against Perl? From asmodai at in-nomine.org Fri Feb 8 09:18:30 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Fri, 8 Feb 2008 15:18:30 +0100 Subject: Time conversion between UTC and local time In-Reply-To: <486ff322-dcb5-4903-a86d-178b8a4d5ce2@e10g2000prf.googlegroups.com> References: <486ff322-dcb5-4903-a86d-178b8a4d5ce2@e10g2000prf.googlegroups.com> Message-ID: <20080208141830.GL39133@nexus.in-nomine.org> -On [20080208 15:16], andreas.profous at googlemail.com (andreas.profous at googlemail.com) wrote: >What is an elegant way of getting the local time (considering DST - >daylight saving time) with that data? Perhaps using pytz might be the easiest way: http://pytz.sourceforge.net/ -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ But Time, keeps flowing like a river (on and on)... From martin at v.loewis.de Tue Feb 19 17:23:12 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 19 Feb 2008 23:23:12 +0100 Subject: Threads vs. continuations In-Reply-To: <061541c8-1f37-42bc-8041-170fee9707b4@h25g2000hsf.googlegroups.com> References: <061541c8-1f37-42bc-8041-170fee9707b4@h25g2000hsf.googlegroups.com> Message-ID: <47BB56D0.2010704@v.loewis.de> > I've been doing some thinking, and I've halfway convinced myself of > the following statement: that threads as implemented by Python (or > Java) are exactly equivalent to one-shot continuations in Scheme. Am > I right? No. In case of threads, progress can be made in an overlapping (concurrent), in case of Java even parallel fashion. In particular, if a thread blocks in a blocking operating system call (e.g. a network receive operation), other threads can continue. I believe this is not possible with continuations in Scheme. In more detail, threads as provided by the operating system underly a system scheduler: they can be preempted, they have priorities, and they may voluntarily block. All this is not possible with continuations. IOW, threads are more expressive than continuations. Regards, Martin From steve at holdenweb.com Thu Feb 21 18:47:42 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 21 Feb 2008 18:47:42 -0500 Subject: Inserting NULL values with pymssql In-Reply-To: <3F533E9AEFD4D343B5EA0E475321F21E03196D36@PDXEX01.webtrends.corp> References: <3F533E9AEFD4D343B5EA0E475321F21E03196D36@PDXEX01.webtrends.corp> Message-ID: Jayson Barley wrote: > I am attempting to insert NULL values into a database. I have tried to > do this in multiple ways without any success, see below, and haven't > been able to find anything through Google to help out. I am hoping that > I am just overlooking something or that it is a rookie mistake. Below is > a test I came up with to prove this. I am on Windows XP using Python 2.5 > and pymssql-0.8.0-py2.5. > > CREATE TABLE [dbo].[Test]( > [test] [varchar](50) NULL, > [inttest] [int] NULL > ) ON [PRIMARY] > > 1. > import pymssql > > TestDB = > pymssql.connect(host='Test',user='test',password='test',database='test') > cursor = TestDB.cursor() > query = """INSERT INTO test.dbo.test VALUES (?, ?);""" > cursor.execute(query,('','')) > Returns > > Traceback (most recent call last): > File "C:\Test\db_info\test.py", line 6, in > cursor.execute(query,('','')) > File "C:\Python25\lib\site-packages\pymssql.py", line 126, in execute > self.executemany(operation, (params,)) > File "C:\Python25\lib\site-packages\pymssql.py", line 152, in executemany > raise DatabaseError, "internal error: %s" % self.__source.errmsg() > pymssql.DatabaseError: internal error: None > > 2. > import pymssql > > TestDB = > pymssql.connect(host='Test',user='test',password='test',database='test') > cursor = TestDB.cursor() > query = """INSERT INTO test.dbo.test VALUES (?, ?);""" > cursor.execute(query,('',None)) > > Returns > > Traceback (most recent call last): > File "C:\Test\db_info\test.py", line 8, in > cursor.execute(query,('',None)) > File "C:\Python25\lib\site-packages\pymssql.py", line 126, in execute > self.executemany(operation, (params,)) > File "C:\Python25\lib\site-packages\pymssql.py", line 152, in executemany > raise DatabaseError, "internal error: %s" % self.__source.errmsg() > pymssql.DatabaseError: internal error: None > > 3. > import pymssql > > TestDB = > pymssql.connect(host='Test',user='test',password='test',database='test') > cursor = TestDB.cursor() > query = """INSERT INTO test.dbo.test VALUES (?, ?);""" > cursor.execute(query,('','NULL')) > Returns > > Traceback (most recent call last): > File "C:\Test\db_info\test.py", line 6, in > cursor.execute(query,('','NULL')) > File "C:\Python25\lib\site-packages\pymssql.py", line 126, in execute > self.executemany(operation, (params,)) > File "C:\Python25\lib\site-packages\pymssql.py", line 152, in executemany > raise DatabaseError, "internal error: %s" % self.__source.errmsg() > pymssql.DatabaseError: internal error: None > > I am wondering what I am missing that is preventing me from inserting a > NULL. I can perform the INSERT in Server Management Studio the problem > only exists in the Python script. If anyone can point me to a resource > that I may have missed or a flaw in my script I would really appreciate it. > What you want is two NULL data values as the second argument to execute(): cursor.execute(query,(None, None)) > I also forgot to mention that this... > > import pymssql > > TestDB = pymssql.connect(host='Test',user='test',password='test',database='test') > cursor = TestDB.cursor() > query = """INSERT INTO test.dbo.test (test) VALUES ('%s');""" > cursor.execute(query,(None)) > > works. While > That's a very naughty database module. It should complain, since you didn't provide a tuple as the second argument to execute(). > import pymssql > > TestDB = pymssql.connect(host='Test',user='test',password='test',database='test') > cursor = TestDB.cursor() > query = """INSERT INTO test.dbo.test (inttest) VALUES ('%d');""" > cursor.execute(query,(None)) > > doesn't work and returns > > Traceback (most recent call last): > File "C:\Test\db_info\test.py", line 6, in > cursor.execute(query,(None)) > File "C:\Python25\lib\site-packages\pymssql.py", line 126, in execute > self.executemany(operation, (params,)) > File "C:\Python25\lib\site-packages\pymssql.py", line 152, in executemany > raise DatabaseError, "internal error: %s" % self.__source.errmsg() > pymssql.DatabaseError: internal error: SQL Server message 245, severity 16, state 1, line 1: > Conversion failed when converting the varchar value '%d' to data type int. > DB-Lib error message 10007, severity 5: > General SQL Server error: Check messages from the SQL Server. I don't know what pymssql's paramstyle is, but I suspect it requires a "%s" far all parameters regardless of their data type. That's SQL Server complaining about the %d, pymssql having failed to recognize it as a parameter marker and passed it through to the engine. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From ilias at lazaridis.com Sat Feb 16 20:59:51 2008 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Sat, 16 Feb 2008 17:59:51 -0800 (PST) Subject: TRAC - Trac, Project Leads, Python, and Mr. Noah Kantrowitz (sanitizer) References: <3d40196b-b1c8-4e18-92f0-7ce5a5a38853__43679.3406880044$1203164550$gmane$org@u72g2000hsf.googlegroups.com> Message-ID: On 16 ???, 15:45, Steve Holden wrote: > Ilias Lazaridis wrote: > > [...]> Of course I'll not stay with trac, I'll leave the sinking ship, I've > > prepare long time ago to do so, step by step. An will migrate step by > > step away from trac and python - toward an own implementation based > > on... > > > perl and it's libraries. > > I'm sure you will find the Perl community much more welcoming and > receptive to your ideas about how open source projects should be run. The perl projects can decide themselfs if they like to adopt the most essential things: http://case.lazaridis.com/wiki/Project I do not analyze languages and communities anymore, thus there is no need for them to 'worry', e.g. that I attemp to transform them to an high evolutive language system. Ruby and Python were excellent for this (Ruby = weak puppets, Python = egoism driven). I'll just use perl until I've implemented my own language, around 2010 to 2011, which will be most possibly close to perl (or a perl extension, if technically possibly and no legal barriers with libraries). Perl is available in nearly every webserver, and has very nice a logical OO functionality (although it's not very good marketed, this OO part). And perl keeps you highly independent, you can work with simple systems, close to the OS. > > Really, I don't understand the need for python. And after fighting > > with some indenting within html templates, I dislike the whitespace- > > syntax-thing of python again. > > Fortunately, as you have realized, you have choices and are under no > compulsion to use any particular tool. As said above: python (essentially it's community in a wider scope) is an ideal domain to analyze how human egoism blocks evolution of technical systems. Thus, python is an important educational tool. > > Do it in perl, if you need something more 'pretty', do it in ruby, if > > you need something more 'serious' do it in java, if you have enough > > brain and time, do it in C++ from bottom up. > > And, apparently, do it in Python if you want to avoind running into > Ilias Lazaridis. No, I'll be bound to python for some time, a year or so. And good news: as I cannot post to the trac-user group, I'll post the topics to comp.lang.python. (you can thank the project lead of trac, his lack of courage is the reason that the developers get out of control) > I have to say your approach to IT systems seems somewhat pedestrian, The IT industry has failed to provide simple standards, systems. AI has failed to produce intelligent systems. So, maybe the IT industry is somewhat pedestrian, as its failure to control egoism has led to terrible software systems. Restarting from the beginning can give the impression of a "learning child". > but I wish you well in whatever it is you are trying to achieve. http://core.lazaridis.com/wiki/ActivityHistory > I hope you have a good set of asbestos (i.e. flame-proof) trousers. As said, the analysis phase is over. But even if not: I've 'survived' within comp.lang.lisp for some months http://groups.google.gr/group/comp.lang.lisp/browse_frm/thread/87980954f111e965/af5f19a1c8101a93?lnk=st&q=dynamite+and+teflon+ilias#af5f19a1c8101a93 I think no language community can be worser. - Btw: If you would adopt the open-source-processes to digital electronic design, we would work today still with 8086. http://case.lazaridis.com/wiki/ProjectLead . From http Wed Feb 27 00:41:16 2008 From: http (Paul Rubin) Date: 26 Feb 2008 21:41:16 -0800 Subject: How about adding rational fraction to Python? References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> Message-ID: <7x63wbez2b.fsf@ruckus.brouhaha.com> Mark Dickinson writes: > > So use: ?return sum(number_list) / float(len(number_list)) > > That makes it somewhat more explicit what you want. ?Otherwise > > But that fails for a list of Decimals... Again, that depends on what your application considers to be failure. Heck, int/int = float instead of decimal might be a failure. FWIW, I just checked Haskell: int/int is not allowed (compile time type error). There is an integer division function `div`, like Python's //, . that you can use if you want an integer quotient. If you want a floating or rational quotient, you have to coerce the operands manually. Explicit is better than implicit. From john.deas at gmail.com Fri Feb 8 04:29:26 2008 From: john.deas at gmail.com (John Deas) Date: Fri, 8 Feb 2008 01:29:26 -0800 (PST) Subject: Chinese character error Message-ID: <7355c3c6-343b-419e-9d01-cc48bb70283e@n20g2000hsh.googlegroups.com> Hi, I made a small script to recursively copy files from a directory tree to an exportDir only if they have an mp3 extension : a=os.walk(os.getcwd()) for root, dirs, files in a: for currFile in files: pathCurrFile=os.path.join(root, currFile) if mp3Reg.search(pathCurrFile): shutil.copy(pathCurrFile,exportDir) else: print pathCurrFile The problem is that I get stuck with files containing name in Chinese : Traceback (most recent call last): File "/cygdrive/c/Documents and Settings/vku/Mes documents/Ma musique/iTunes/i Tunes Music/script.py", line 21, in shutil.copy(pathCurrFile,exportDir) File "/usr/lib/python2.5/shutil.py", line 80, in copy copyfile(src, dst) File "/usr/lib/python2.5/shutil.py", line 46, in copyfile fsrc = open(src, 'rb') IOError: [Errno 2] No such file or directory: '/cygdrive/c/Documents and Setting s/vku/Mes documents/Ma musique/iTunes/iTunes Music/Podcasts/Learn Chinese - Chin esePod/785 Advanced - ????.mp3' I am using python on cygwin, so could this be the source of the error, and is there a way to fix this ? From http Fri Feb 22 00:39:35 2008 From: http (Paul Rubin) Date: 21 Feb 2008 21:39:35 -0800 Subject: Return value of an assignment statement? References: <6d945394-739e-4c47-ad71-faaab8f9d566@34g2000hsz.googlegroups.com> <5sudnTSXrZY0aCDanZ2dnUVZ_rKtnZ2d@comcast.com> <5MSdncSVGdGriCPanZ2dnUVZ_vPinZ2d@comcast.com> Message-ID: <7xskzlczxk.fsf@ruckus.brouhaha.com> Jeff Schwab writes: > So what is the "variable?" Or is Python the first HLL I've ever heard > of that didn't have variables? I don't know what other HLL's you use, but some languages don't even have mutable values. From mwilson at the-wire.com Mon Feb 4 09:10:21 2008 From: mwilson at the-wire.com (Mel) Date: Mon, 04 Feb 2008 09:10:21 -0500 Subject: type, object hierarchy? References: <814a05b4-6f13-4c86-8c68-a30da06ca093@b2g2000hsg.googlegroups.com> <2ba95819-0699-49c6-b7e9-96d54763be52@v17g2000hsa.googlegroups.com> <4a2fabf4-5a4d-4afc-a722-f2887da10d1f@q39g2000hsf.googlegroups.com> Message-ID: 7stud wrote: > On Feb 3, 10:28 pm, 7stud wrote: >> From the docs: >> >> issubclass(class, classinfo) >> Return true if class is a subclass (direct or indirect) of classinfo. > > > print issubclass(Dog, object) #True > print issubclass(type, object) #True > print issubclass(Dog, type) #False Python 2.5.1 (r251:54863, Oct 5 2007, 13:36:32) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> issubclass (object, type) False >>> isinstance (object, type) True From benhoyt at gmail.com Mon Feb 18 17:28:43 2008 From: benhoyt at gmail.com (benhoyt) Date: Mon, 18 Feb 2008 14:28:43 -0800 (PST) Subject: Double underscores -- ugly? Message-ID: Hi guys, I've been using Python for some time now, and am very impressed with its lack of red tape and its clean syntax -- both probably due to the BDFL's ability to know when to say "no". Most of the things that "got me" initially have been addressed in recent versions of Python, or are being addressed in Python 3000. But it looks like the double underscores are staying as is. This is probably a good thing unless there are better alternatives, but ... Is it just me that thinks "__init__" is rather ugly? Not to mention "if __name__ == '__main__': ..."? I realise that double underscores make the language conceptually cleaner in many ways (because fancy syntax and operator overloading are just handled by methods), but they don't *look* nice. A solution could be as simple as syntactic sugar that converted to double underscores behind the scenes. A couple of ideas that come to my mind (though these have their problems too): def ~init(self): # shows it's special, but too like a C++ destructor def +init(self): # a bit too additive :-) defop add(self, other): # or this, equivalent to "def __add__" def operator add(self, other): # new keyword, and a bit wordy Has anyone thought about alternatives? Is there a previous discussion on this I can look up? Cheers, Ben. From usenet at ionline.dk Wed Feb 27 13:45:53 2008 From: usenet at ionline.dk (ndlarsen) Date: Wed, 27 Feb 2008 19:45:53 +0100 Subject: Print to end of line in a terminal Message-ID: <47c5afe4$0$90273$14726298@news.sunsite.dk> Hey. This might seem as a arbitrary question to some. Anyway, I'm wondering how I go about printing text to the end of a line in a terminal/console. I've been googling it for a few days without any success. Any suggestions will be greatly appreciated. Regards ndlarsen From mal at egenix.com Wed Feb 20 11:05:18 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Wed, 20 Feb 2008 17:05:18 +0100 Subject: Handling locked db tables... In-Reply-To: <6768beab-566e-4d0e-94c9-a4def273d467@m23g2000hsc.googlegroups.com> References: <6768beab-566e-4d0e-94c9-a4def273d467@m23g2000hsc.googlegroups.com> Message-ID: <47BC4FBE.5050705@egenix.com> On 2008-02-20 16:24, breal wrote: > I have a db table that holds a list of ports. There is a column > in_use that is used as a flag for whether the port is currently in > use. When choosing a port the table is read and the first available > port with in_use = 0 is used, updated to in_use = 1, used, then > updated to in_use = 0. I am using MySQLdb and want to make sure I am > locking the table when doing reads, writes, updates since there will > be several instances of my program looking for available ports > simultaneously. > > When I run a "lock table mytable read" I can do all of my > transactions. But, when another cursor then tries to do the read I > get an error unless the first process has been completed... unlocking > the tables. How is this handled generally? This is normal database locking behavior. If you do an update to a table from one process, the updated row is locked until the transaction is committed. If another process wants to access that row (even if only indirectly, e.g. a select that does a query which includes the data from the locked row), that process reports a database lock or times out until the lock is removed by the first process. The reason is simple: you don't want the second process to report wrong data, since there's still a chance the first process might roll back the transaction. Most modern database allow row-level locking. I'm not sure whether MySQL supports this. SQLite, for example, only support table locking. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Feb 20 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From rw at smsnet.pl Fri Feb 22 13:42:40 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Fri, 22 Feb 2008 19:42:40 +0100 Subject: n00b with urllib2: How to make it handle cookie automatically? References: Message-ID: <87pruorfxb.fsf@merkury.smsnet.pl> est writes: > Hi all, > > I need urllib2 do perform series of HTTP requests with cookie from > PREVIOUS request(like our browsers usually do ). Many people suggest I > use some library(e.g. pycURL) instead but I guess it's good practise > for a python beginner to DIY something rather than use existing tools. > > So my problem is how to expand the urllib2 class > > from cookielib import CookieJar > class SmartRequest(): > cj=CookieJar() > def __init__(self, strUrl, strContent=None): > self.Request = urllib2.Request(strUrl, strContent) > self.cj.add_cookie_header(self.Request) > self.Response = urllib2.urlopen(Request) > self.cj.extract_cookies(self.Response, self.Request) > def url > def read(self, intCount): > return self.Response.read(intCount) > def headers(self, strHeaderName): > return self.Response.headers[strHeaderName] > > The code does not work because each time SmartRequest is initiated, > object 'cj' is cleared. How to avoid that? > The only stupid solution I figured out is use a global CookieJar > object. Is there anyway that could handle all this INSIDE the class? > > I am totally new to OOP & python programming, so could anyone give me > some suggestions? Thanks in advance Google for urllib2.HTTPCookieProcessor. HTH, Rob From bignose+hates-spam at benfinney.id.au Mon Feb 18 07:31:15 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 18 Feb 2008 23:31:15 +1100 Subject: decode Numeric Character References to unicode References: Message-ID: <87skzqla3w.fsf@benfinney.id.au> 7stud writes: > For instance, an 'o' with umlaut can be represented in three > different ways: > > '&' followed by 'ouml;' > '&' followed by '#246;' > '&' followed by '#xf6;' The fourth way, of course, is to simply have '?' appear directly as a character in the document, and set the correct character encoding. (Hint: UTF-8 is an excellent choice for "the correct character encoding", if you get to choose.) -- \ ?With Lisp or Forth, a master programmer has unlimited power | `\ and expressiveness. With Python, even a regular guy can reach | _o__) for the stars.? ?Raymond Hettinger | Ben Finney From michael.pearmain at tangozebra.com Tue Feb 12 05:21:49 2008 From: michael.pearmain at tangozebra.com (Mike P) Date: Tue, 12 Feb 2008 02:21:49 -0800 (PST) Subject: CSV Reader References: <43a3a0d8-9425-4bc5-90d3-894fe980d3f7@s19g2000prg.googlegroups.com> <4b1e691a-53ff-4cee-8e15-5bf17f2b56ef@i12g2000prf.googlegroups.com> Message-ID: I did just try to post, but it doesn't look like it has appeared? I've used your advice Andrew and tried to use the CSV module, but now it doesn't seem to pick up the startswith command? Is this because of the way the CSV module is reading the data in? I've looked into the module description but i can't find anything that i hould be using? Can anyone offer an advice? Cheers again Mike working_CSV = "//filer/common/technical/Research/E2C/Template_CSV/ DFAExposureToConversionQueryTool.csv" save_file = "//filer/common/technical/Research/E2C/Template_CSV/ CSV_Data2.csv" start_line=False import csv reader = csv.reader(open(working_CSV, "rb")) writer = csv.writer(open(save_file, "wb")) for row in reader: if not start_line and record.startswith("'Transaction ID'"): start_line=True if start_line: print row writer.writerows(rows) #writer.close() From arnodel at googlemail.com Tue Feb 26 17:00:03 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 26 Feb 2008 14:00:03 -0800 (PST) Subject: How about adding rational fraction to Python? References: <0d1955fc-762c-44e1-a5d8-372c71458455@p25g2000hsf.googlegroups.com> <36204e6f-0d82-449b-8ca5-c819ace9a55a@p73g2000hsd.googlegroups.com> <9503b14b-7bd5-42b4-b3f7-673d0ebd7feb@c33g2000hsd.googlegroups.com> <602ac27c-4aaa-49b2-bee2-1e0e0c705983@i7g2000prf.googlegroups.com> <1204034122.3318.3.camel@aalcdl07.lib.unc.edu> <874pbvvhu1.fsf@mulj.homelinux.net> <13s927o65an9b58@corp.supernews.com> Message-ID: On Feb 26, 9:47?pm, Steven D'Aprano wrote: > On Tue, 26 Feb 2008 11:43:56 -0500, D'Arcy J.M. Cain wrote: > > Integer division means integer result to me in a very real sense. > > So, when you have five children over for a birthday party, and one cake, > do you say "Sorry kids, no cake for you: one cake divided by five is > zero"? > > Of course you do, you big meanie. I think you catered for my 12th > birthday party. Whereas I bet you would be able to share the cake equally and each child would get 0.20000000000000001 of a cake :) Or perhaps it would be better to have 2**n guests... Or maybe one should think of the cake as 1.0 cake, as experience shows that cakes can be cut... -- Arnaud From steve at holdenweb.com Sat Feb 9 00:29:35 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 09 Feb 2008 00:29:35 -0500 Subject: Help Wanted (Volunteer(s)) Message-ID: The Job Board needs you, please see http://pyfound.blogspot.com/2008/02/help-needed-with-python-job-board.html regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From tjreedy at udel.edu Mon Feb 25 15:42:51 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 25 Feb 2008 15:42:51 -0500 Subject: Using lambda [was Re: Article of interest: Python pros/cons fortheenterprise] References: <47bd4a24$0$25225$426a74cc@news.free.fr><036e93e6-5840-4a3c-8642-67a0a9ec44f2@i7g2000prf.googlegroups.com><784ec210-f389-4a15-b458-961100de9103@v3g2000hsc.googlegroups.com><5MSdncqVGdEXiSPanZ2dnUVZ_vPinZ2d@comcast.com><7xwsoxd00c.fsf@ruckus.brouhaha.com><7xmyprtay1.fsf@ruckus.brouhaha.com><88qdnQR0a7V7Rl3anZ2dnUVZ_rqlnZ2d@comcast.com><7xmyprf3ef.fsf@ruckus.brouhaha.com> <13s5kclk4maa584@corp.supernews.com> Message-ID: "Steven D'Aprano" wrote in message news:13s5kclk4maa584 at corp.supernews.com... | On Sun, 24 Feb 2008 21:13:08 -0500, Terry Reedy wrote: | | > | I even use "named anonymous functions" *cough* by assigning lambda | | > functions to names: | > | | > | foo = lambda x: x+1 | > | > Even though I consider the above to be clearly inferior to | > | > def foo(x): return x+1 | > | > since the latter names the function 'foo' instead of the generic | > ''. | | Absolutely. If foo() was a function that the user would see, I would | certainly use the def form to create it. | | But in a situation like this: | | | def parrot(x, y, z, func=None): | if func is None: | func = lambda x: x+1 | return func(x+y+z) Since functions are constants with respect to code attribute, you might as well condense that to def parrot(x,y,z, func = lambda xyz: xyz+1): return func(x+y+z) Then you can claim some actual space saving. | I don't see any advantage to writing it as: | | def parrot(x, y, z, func=None): | if func is None: | def func(x): return x+1 | return func(x+y+z) Good habit? Don't mislead the newbies ;-? tjr From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Feb 14 09:26:02 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 14 Feb 2008 15:26:02 +0100 Subject: Running CGI from within CGI In-Reply-To: <703e55c2-00c0-43a6-9f67-988994ac44b9@e23g2000prf.googlegroups.com> References: <703e55c2-00c0-43a6-9f67-988994ac44b9@e23g2000prf.googlegroups.com> Message-ID: <47b44f3e$0$29332$426a34cc@news.free.fr> rodmc a ?crit : > I am new to using Python as a CGI platform, so please excuse me if > this is a dumb question. > > Anyway I have written a series of web forms (with Python scripts) > which allow the user input but also retrieve data from a database. The > data entry stage works fine however retrieving data is a little more > tricky. However I need to find a way to call the scripts directly from > within other CGI's. At present when I go to the next page I call the > normal HTML page as below: > > p = open('somefile.html') > some = p.read() > p.close() > print some > > > However I would like to execute a script instead so calling for > example myscript.py - thus populating the existing forms with data. > This does not seem to work when I modify the above method. Is there > another way to do it? Thanks in advance. The QuickAndDirtyWay(tm) would be to use execfile IIRC. But since you *don't* want to do it that way, the best thing to do would be to factor out common code into functions in a distinct module (or in as many modules as needed), then rewrite your cgi scripts so they import the relevant modules and call the appropriate functions. And while we're at it, I'd greatly recommand giving a look at the various templating packages around (may I recommand Mako ?) and the FormEncode package for HTTP forms conversion/validation ? HTH From wolf_tracks at invalid.com Sun Feb 17 22:33:44 2008 From: wolf_tracks at invalid.com (W. Watson) Date: Mon, 18 Feb 2008 03:33:44 GMT Subject: Pmw Use and Grayson's Book Message-ID: I don't have Grayson's Tkinter book, but I see he uses something called Pmw. Why is it needed with Tkinter? -- Wayne Watson (Nevada City, CA) Web Page: From jzgoda at o2.usun.pl Tue Feb 19 04:32:32 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Tue, 19 Feb 2008 10:32:32 +0100 Subject: Garbage collection In-Reply-To: References: Message-ID: Duncan Booth napisa?(a): > Pretty much. If you have a __del__ method on an object then in the worst > case the only thing that can be guaranteed is that it will be called zero, > one or more than one times. (Admittedly the last of these only happens if > you work at it). > > If it is called then is may be either immediately the last reference to the > object is lost, or it may be later when the garbage collector runs (and not > necessarily the first next time the garbage collector runs). Java finalizers are not called upon VM exit, only when object is swept by GC (for example when the object is destroyed upon program exit), the CPython docs read that this is the case for Python too. Is this behaviour standard for all VM implementations or is implementation-dependent (CPython, Jython, IronPython)? -- Jarek Zgoda Skype: jzgoda | GTalk: zgoda at jabber.aster.pl | voice: +48228430101 "We read Knuth so you don't have to." (Tim Peters) From bockman at virgilio.it Mon Feb 25 07:26:15 2008 From: bockman at virgilio.it (bockman at virgilio.it) Date: Mon, 25 Feb 2008 04:26:15 -0800 (PST) Subject: Newbie: How can I use a string value for a keyword argument? References: Message-ID: <94d32501-c16c-4609-a834-5ad60afa00f7@s12g2000prg.googlegroups.com> On 25 Feb, 12:42, Doug Morse wrote: > Hi, > > My apologies for troubling for what is probably an easy question... it's just > that can't seem to find an answer to this anywhere (Googling, pydocs, etc.)... > > I have a class method, MyClass.foo(), that takes keyword arguments. ?For > example, I can say: > > x = MyClass() > x.foo(trials=32) > > Works just fine. > > What I need to be able to do is call foo() with a string value specifying the > keyword (or both the keyword and value would be fine), something along the > lines of: > > x = MyClass() > y = 'trials=32' > x.foo(y) ? ? ? ?# doesn't work > > or > > x.MyClass() > y = 'trials' > x.foo(y = 32) ? # does the "wrong" thing > Try this: y='trials' x.foo( **{y:32} ) Ciao ----- FB From bbxx789_05ss at yahoo.com Thu Feb 28 06:50:56 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Thu, 28 Feb 2008 03:50:56 -0800 (PST) Subject: more pythonic References: Message-ID: <4200e44a-0859-44b2-af04-68e9c9e98da6@s12g2000prg.googlegroups.com> On Feb 28, 4:48?am, 7stud wrote: > > It's my understanding that the way you insert arguments into queries > has to be done in a db specific way. ? > Rather: It's my understanding that the way you insert arguments into queries *should* be done in a db specific way. ? From stefan_ml at behnel.de Sat Feb 2 09:48:28 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 02 Feb 2008 15:48:28 +0100 Subject: REALLY simple xml reader In-Reply-To: <13q8p3nn7pi9hd9@corp.supernews.com> References: <1090e4100801271040n7bc6b452n346adee02abcd91d@mail.gmail.com> <60do34F1q1qmlU1@mid.uni-berlin.de> <60dsbrF1qj28sU1@mid.uni-berlin.de> <87tzkujeq6.fsf@benfinney.id.au> <13q3ri2707niqc6@corp.supernews.com> <87odb1k9ar.fsf@benfinney.id.au> <13q8p3nn7pi9hd9@corp.supernews.com> Message-ID: <47A482BC.2080907@behnel.de> Steven D'Aprano wrote: > On Fri, 01 Feb 2008 07:51:56 +1100, Ben Finney wrote: > >> Steven D'Aprano writes: >> >>> On Fri, 01 Feb 2008 00:40:01 +1100, Ben Finney wrote: >>> >>>> Quite apart from a human thinking it's pretty or not pretty, it's >>>> *not valid XML* if the XML declaration isn't immediately at the start >>>> of the document . Many >>>> XML parsers will (correctly) reject such a document. >>> You know, I'd really like to know what the designers were thinking when >>> they made this decision. >> Probably much the same that the designers of the Unix shebang ("#!") or >> countless other "figure out whether the bitstream is a specific type" >> were thinking: > > There's no real comparison with the shebang '#!'. It is important that > the shell can recognise a shebang with a single look-up for speed, and > the shell doesn't have to deal with the complexities of Unicode: if you > write your script in UTF-16, bash will complain that it can't execute the > binary file. The shell cares whether or not the first two bytes are 23 > 21. An XML parser doesn't care about bytes, it cares about tags. Or rather about unicode code points. I actually think that you can compare the two. The shell can read the shebang, recognise it, and continue reading up to the first newline to see what needs to be done. That's one simple stream, no problem. Same for the XML parser. It reads the stream and it will not have to look back, even if the declaration requests a new encoding. Just like the shebang has to be at the beginning, the declaration has to be there, too. All I'm saying is that there is a point where you have to draw the line, and the XML spec says, that the XML declaration must be at the beginning of the document, and that it may be followed by whitespace. I think that's clear and simple. It admit that it's questionable if it should be allowed to omit the declaration, but since there is only one case where you are allowed to do that, I'm somewhat fine with this special case. Stefan From muthusamypearlpost at gmail.com Sat Feb 9 05:21:06 2008 From: muthusamypearlpost at gmail.com (sam) Date: Sat, 9 Feb 2008 02:21:06 -0800 (PST) Subject: online marketing make money Message-ID: <36469d35-884e-487b-a2fa-dd679629cd19@s8g2000prg.googlegroups.com> It is new one online business you can earn minimum 1000$ per month great oppertunity to students,house wives,retired persons andall others . http://onlinemarketingmakemoney.blogspot.com From davidson.kris at gmail.com Wed Feb 27 22:39:24 2008 From: davidson.kris at gmail.com (Kris Davidson) Date: Thu, 28 Feb 2008 03:39:24 +0000 Subject: Python IRC Zork Message-ID: Hi, If this has been done before in another language could someone please tell me, if not I was wondering is its possible and what the easier way is to create an IRC bot that allows you to play Zork: I was thinking of just creating a simple Python IRC bot or finding an existing one then have it run Zork and read/write from stdout/stdin. Is that possible? Is there a better or easier way to do it? Are there any existing programs that do something similar? Or just really anything else people have to say on the subject. Thanks Kris From larry.bates at websafe.com Mon Feb 4 10:29:44 2008 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 04 Feb 2008 09:29:44 -0600 Subject: Too many open files In-Reply-To: <47a70bd0$0$3908$426a74cc@news.free.fr> References: <47a70bd0$0$3908$426a74cc@news.free.fr> Message-ID: <1radnXQzePvtsjranZ2dnUVZ_oTinZ2d@comcast.com> AMD wrote: > Hello, > > I need to split a very big file (10 gigabytes) into several thousand > smaller files according to a hash algorithm, I do this one line at a > time. The problem I have is that opening a file using append, writing > the line and closing the file is very time consuming. I'd rather have > the files all open for the duration, do all writes and then close them > all at the end. > The problem I have under windows is that as soon as I get to 500 files I > get the Too many open files message. I tried the same thing in Delphi > and I can get to 3000 files. How can I increase the number of open files > in Python? > > Thanks in advance for any answers! > > Andre M. Descombes Not quite sure what you mean by "a hash algorithm" but if you sort the file (with external sort program) on what you want to split on, then you only have to have 1 file at a time open. -Larry From MartinRinehart at gmail.com Thu Feb 28 09:33:33 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Thu, 28 Feb 2008 06:33:33 -0800 (PST) Subject: Python's BNF References: <85ae78f6-056b-4219-9952-66750e3ebf58@e60g2000hsh.googlegroups.com> Message-ID: Implemented all your suggestions, with two exceptions. Changed file read to readlines(), but not open(...).readlines(). I love to say file.close(). Gives me a feeling of security. (We could discuss RAM waste v. I/O speed but this input file is just 10KB, so neither matters.) Removed one of the three globals, but left the other two. Couldn't see any real advantage to passing poor 'ofile' from hand to hand (writeHTML() to writeBody() to writeEntries() ...) as opposed to letting him rest easy in his chair, doing a little writing when called. Also changed the opening doc comment to give you appropriate credit. Thanks again. From andreas.profous at googlemail.com Fri Feb 8 09:10:14 2008 From: andreas.profous at googlemail.com (andreas.profous at googlemail.com) Date: Fri, 8 Feb 2008 06:10:14 -0800 (PST) Subject: Time conversion between UTC and local time Message-ID: <486ff322-dcb5-4903-a86d-178b8a4d5ce2@e10g2000prf.googlegroups.com> Hi all, I have the following problem: There are strings describing a UTC time, e.g. " 2008-01-15 22:32:30" and a string reflecting the time zone e.g. "-05:00". What is an elegant way of getting the local time (considering DST - daylight saving time) with that data? The date is not important, just the local time. The format is not important, the easiest would probably be a tuple (h,m,s) . Thanks in advance From nagle at animats.com Mon Feb 4 14:30:41 2008 From: nagle at animats.com (John Nagle) Date: Mon, 04 Feb 2008 11:30:41 -0800 Subject: Very weird behavior in MySQLdb "execute" Message-ID: <47a76661$0$36336$742ec2ed@news.sonic.net> This has me completely mystified. Some SELECT operations performed through MySQLdb produce different results than with the MySQL graphical client. This failed on a Linux server running Python 2.5, and I can reproduce it on a Windows client running Python 2.4. Both are running MySQL 2.5. The table involved is: CREATE TABLE domaincache ( domain VARCHAR(255) NOT NULL UNIQUE PRIMARY KEY, rating CHAR(1) NULL, rating_info ENUM ('error','no_domain','no_website','blocked','no_location','negative_info','non_commercial','unverified') NULL, special_case ENUM('normal','special'), rating_id BIGINT UNSIGNED NULL, last_update_end TIMESTAMP NOT NULL, version SMALLINT UNSIGNED NOT NULL, INDEX (rating_id) ); Nothing exciting there. In the MySQL query browser, I can do either select * from domaincache where domain = "adwords.google.com" or select * from domaincache where domain = "google.com" and I get one record back from each, with the correct info. That's correct. Querying the database from Python gives different results. The database connection is made with: db = MySQLdb.connect(host="localhost", use_unicode = True, charset = "utf8", user=username, passwd=password, db=database) When I make the same queries from Python, via IDLE, typing in commands: cursor.execute('SELECT * FROM domaincache WHERE domain="adwords.google.com"') returns 0L, no rows, which is wrong. That domain is in the database, and a SELECT from the graphical client will find it. But cursor.execute('SELECT * FROM domaincache WHERE domain="google.com"') returns 1L, one row, which is correct. The database is InnoDB, and CHECK TABLE says the database is valid. Restarting the MySQL instance changes the database. The entry "google.com" disappears, and is replaced by "www.google.com". This must indicate a hanging transaction that wasn't committed. But that transaction didn't come from the Python IDLE session I've been making test calls from. Those queries should match the graphical client exactly. So why don't they agree? From ivan.illarionov at gmail.com Wed Feb 20 00:50:33 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Tue, 19 Feb 2008 21:50:33 -0800 (PST) Subject: Double underscores -- ugly? References: Message-ID: <360395fe-dd12-45eb-a40b-99c7a9e89dcf@v3g2000hsc.googlegroups.com> I would like to see something like %init or &init to be converted to __init__ behind the scenes. And $something to be converted to self.something. But, unfortunately, most Python people would consider this ugly just because Perl uses too much syntactic sugar and anything Perl-like is considered ugly in Python community. So, unless Perl die, I believe that Python will remain sugar-free. From t at nomail.com Sat Feb 16 15:28:00 2008 From: t at nomail.com (T_T) Date: 16 Feb 2008 20:28:00 GMT Subject: simple python script to zip files References: <47b7032c$0$54085$dbd4b001@news.wanadoo.nl> <47b70407$0$54085$dbd4b001@news.wanadoo.nl> <47b73aa3$0$54085$dbd4b001@news.wanadoo.nl> Message-ID: <47b74750$0$54085$dbd4b001@news.wanadoo.nl> > f = zipfile.ZipFile(zipfilename, 'w', > compression=zipfile.ZIP_DEFLATED) > > -tkc Adding the compression rule works great, thanks again! From ndbecker2 at gmail.com Sat Feb 9 17:03:53 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Sat, 09 Feb 2008 17:03:53 -0500 Subject: Turn off ZeroDivisionError? Message-ID: I'd like to turn off ZeroDivisionError. I'd like 0./0. to just give NaN, and when output, just print 'NaN'. I notice fpconst has the required constants. I don't want to significantly slow floating point math, so I don't want to just trap the exception. If I use C code to turn off the hardware signal, will that stop python from detecting the exception, or is python checking for 0 denominator on it's own (hope not, that would waste cycles). From spamspam at spam.eggs Tue Feb 12 17:17:05 2008 From: spamspam at spam.eggs (Ben C) Date: Tue, 12 Feb 2008 16:17:05 -0600 Subject: Recursive generator References: <7x63wt5310.fsf@ruckus.brouhaha.com> Message-ID: On 2008-02-12, Paul Rubin <> wrote: > Paul Hankin writes: >> def genDescendants(self): >> return chain([self], *[child.genDescendants() >> for child in self.children]) > > That is scary. It generates an in-memory list the size of the > whole subtree, at every level. Total memory consumption is maybe > even quadratic, depending on the tree shape, but even if it's > only linear, it's way ugly. This would probably be better (in terms of memory if not beauty): def genDescendants(self): return chain([self], *(child.genDescendants() for child in self.children)) From noname9968 at gmail.com Sat Feb 9 07:18:17 2008 From: noname9968 at gmail.com (Alex) Date: Sat, 09 Feb 2008 15:18:17 +0300 Subject: Edit Python code programmatically In-Reply-To: <13qr5h970g2mrba@corp.supernews.com> References: <13qr5h970g2mrba@corp.supernews.com> Message-ID: <47AD9A09.3060603@gmail.com> Steven D'Aprano wrote: > On Sat, 09 Feb 2008 14:38:29 +0300, Alex wrote: > > >> Which library could you recommend to perform simple editing of Python >> code (from Python program)? >> > > I'm not even sure such a library exists. > Yes they exist, that field is called "code-generation", "generative programming" etc. > > >> For example, open *.py file, find specific >> function definition, add another function call inside, find existing >> call and change parameter value, etc. >> > > Why do you want to do that? I'm not sure what you're trying to > accomplish. Code refactoring? I imagine that's probably best done with > your text editor: at best, your editor will have dedicated refactoring > tools, and at worst, it will have global search and replace. I don't feel like describing all ideas - it's nothing really intersting anyway, just a learning project (to get to know language features), but obviously it's not for regular programming - I know text editors can do that just fine. Simply in some situation I think instead of generating data I'd better generate some code. From wolf_tracks at invalid.com Tue Feb 12 00:37:11 2008 From: wolf_tracks at invalid.com (W. Watson) Date: Mon, 11 Feb 2008 21:37:11 -0800 Subject: Is there a web visitor counter available in Python ... In-Reply-To: References: Message-ID: <6easj.124$tW.106@nlpi070.nbdc.sbc.com> PHP. Well, that's a new one on me. Google gave me some idea of what it's about, and I found some code on how to do it. It requires yet another "programming language", which means finding the editor, etc. Jon "Fluffy" Saul wrote: > On Feb 11, 2008 9:21 PM, W. Watson wrote: >> ... that is free for use without advertising that I can use on my web pages? >> I have no idea is suitable for this. My knowledge of Python is somewhat >> minimal at this point. Maybe Java is better choice. >> >> -- >> Wayne Watson (Nevada City, CA) >> >> Web Page: >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > PHP would be the best choice. > Simple and advanced PHP hit counters can be found with a search of Google. > "PHP hit counter", etc. > -- Wayne Watson (Nevada City, CA) Web Page: From jeff at schwabcenter.com Sat Feb 9 16:29:13 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Sat, 09 Feb 2008 13:29:13 -0800 Subject: sort functions in python In-Reply-To: <13qqnga820l8991@corp.supernews.com> References: <13qq49c705dnc2a@corp.supernews.com> <13qqnga820l8991@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > On Fri, 08 Feb 2008 19:09:06 -0800, Jeff Schwab wrote: > >> Steven D'Aprano wrote: >>> On Fri, 08 Feb 2008 17:00:27 -0800, t3chn0n3rd wrote: >>> >>>> Do you think it is relatively easy to write sort algorithms such as >>>> the common Bubble sort in Python as compared to other high level >>>> programming langauges >>> >>> You realise that bubble sort is one of the worst possible sort >>> algorithms possible, particularly on modern hardware? It's not the >>> worst: bogo sort and bozo sort are worse, but bubble sort is still >>> pretty atrocious. >> That's the conventional wisdom, mostly because CS professors need a "bad >> algorithm" to show undergrads, but it's not really accurate. The truth >> is that bubble-sort's performance depends strongly on the input data. In >> the worst case, yes, bubble-sort is O(n^2); however, for almost-sorted >> data (only a few elements out of place), bubble-sort is actually one of >> the fastest known algorithms. > > It depends on what you mean by "bubble sort". There are many different > variations of bubble sort, that are sometimes described by names such as > comb sort, cocktail sort, exchange sort, and sometimes merely referred to > bubble sort. It's rather like any divide-and-conquer sorting algorithm > being called quicksort. > > I'm as guilty of that as anyone else -- the example code I posted, raided > from Wikibooks is very different from this bubble sort algorithm from > PlanetMath: > > http://planetmath.org/encyclopedia/Bubblesort.html > > def bubblesort(L): > done = False > while not done: > done = True > for i in xrange(len(L)-1): > if L[i+1] <= L[i]: > L[i], L[i+1] = L[i+1], L[i] > done = False > return L > > This one runs significantly faster than the earlier one I posted. > > Another vital factor is, what language are you implementing the sort > routine in? The conventional wisdom for low-level languages like assembly > and C doesn't necessarily hold for high-level languages like Python. > Comparisons are slow in Python and fast in C; in C a good algorithm will > minimize the amount of moves, while in Python a good algorithm will > minimize the number of comparisons. > > Finally, what hardware are you running on? There are interactions between > hardware caches and pipes that can ruin the performance of an otherwise > promising algorithm. > > > But all those factors aside, I fear that your attempt to rehabilitate the > reputation of bubble sort is misplaced. Here's another person who wants > to defend bubble sort: > > "A fair number of algorithm purists (which means they've probably never > written software for a living) claim that the bubble sort should never be > used for any reason. Realistically, there isn't a noticeable performance > difference between the various sorts for 100 items or less, and the > simplicity of the bubble sort makes it attractive." > > http://linux.wku.edu/~lamonml/algor/sort/bubble.html > > But then on the same person's page on insertion sort: > > "The insertion sort is a good middle-of-the-road choice for sorting lists > of a few thousand items or less. The algorithm is significantly simpler > than the shell sort, with only a small trade-off in efficiency. At the > same time, the insertion sort is over twice as fast as the bubble sort > and almost 40% faster than the selection sort." > > http://linux.wku.edu/~lamonml/algor/sort/insertion.html > > He gives sample C code for both, and the bubble sort has eight lines of > code, versus nine for insertion sort (excluding bare braces). > > Perhaps what he should have said is: > > "Bubble sort is a tiny bit simpler than insertion sort, and almost twice > as slow!" So basically, you and I agree that the right sorting algorithm for the job depends on the job. I have no particular interest in evangelizing for bubble-sort; however, I hate to see an algorithm (or data structure, or language, or programming style) taken out of the running before the race even starts, just because it's out of fashion. From Graham.Dumpleton at gmail.com Tue Feb 19 21:28:05 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Tue, 19 Feb 2008 18:28:05 -0800 (PST) Subject: problem with mod_python References: <20080217042915.GA24617@debian> Message-ID: <3447f312-87cb-4060-8bd6-78b7b5d1ea09@c33g2000hsd.googlegroups.com> On Feb 20, 6:04 am, Joshua Kugler wrote: > Pradnyesh Sawant wrote: > > Hello, > > I have a small program which does 'import hashlib'. This program runs fine > > with python2.5. But when I try running the same program through > > mod_python, I get the error: 'ImportError: No module named hashlib' in the > > apache2 error.log > > > Searching online suggested me to include md5.so or md5module.so in > > apache2. but I don't see that in a package for debian lenny (the system > > I'm using). > > > So, my Q is, is it possible to make mod_python use the same PYTHONPATH as > > the python2.5 interpreter? if so, how? > > It sounds like your mod_python may be compiled against a different version > of Python than your main installation? How did you install mod_python? How > did you install your main python installation? > > What is the output of the command: > > ldd /path/to/mod_python.so > > (the full path on my system is /usr/lib/apache2/mod_python.so) > > There should be a line something like: > > libpython2.5.so.1.0 => /usr/lib/libpython2.5.so.1.0 (0xb7e37000) > > If it is pointing to libpython.2.4.so.1.0, then that could be the reason for > you troubles. The ldd trick only works if the Python version being used actually supplied a shared library and mod_python was able to link against it, otherwise a static version of Python is embedded in mod_python. Some Linux distributions still possibly don't provide a shared library for Python, or don't correctly symlink the .so into the Python config directory along side the .a so that linkers will find it correctly when -L for config directory is used. This has in part been the fault of Python itself as build from source doesn't necessarily do that symlink. Not sure if this has changed in more recent Python versions. Graham From tim.arnold at sas.com Fri Feb 1 14:47:24 2008 From: tim.arnold at sas.com (Tim Arnold) Date: Fri, 1 Feb 2008 14:47:24 -0500 Subject: build tool opinions Message-ID: Hi, I'm going through the various build tools (i.e., make-like) available and could use some advice. My documentation-build system is written in python and uses the pdflatex and plasTeX engines to create pdfs, html, and docbook XML from latex source files. All that is ok, but I can clean up a lot of code by letting a build tool take care of installing the doc, creating build dirs, interacting with the CMS, etc. So I started out looking at ant, since it's so popular. That led me on to look at SCons since it's written in python, and that led me on to look at 'A-A-P'. Well, there's a lot of options out there. So my question is what should I use? Impossible to answer I know, but it looks like SCons and A-A-P haven't had a lot of development activity--that seems to be because they're stable, not because they've been abandoned. Right now I like the fact that SCons and A-A-P are both written in Python; On the other hand I think I could use Jython and Ant too. Any ideas/opinions/advice would be helpful. --Tim From gagsl-py2 at yahoo.com.ar Thu Feb 28 22:43:37 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 29 Feb 2008 01:43:37 -0200 Subject: (Newbie) Help with sockets. References: <146eb331-a79a-4ac7-ba29-a9935643b20f@d4g2000prg.googlegroups.com> Message-ID: En Fri, 29 Feb 2008 00:20:26 -0200, escribi?: > Hi everyone. I'm fairly new to Python, and even more new to socket > programming. I think I've wrapped my head around sockets, and with > that I want to create a Telnet-based chat server, the idea being > people connect to the telnet servers with their clients and they all > communicate. I've got the code working, but the server sends each > letter to the clients on a new line! I've read about this kind of > thing on Windows on Google, but I can't find a solution to this issue. The telnet client can use "line mode" or "character mode". In "line mode" nothing is sent until the user press Enter; line editing is made on the client side. In "character mode" keystrokes are sent as soon as typed; probably your telnet client is using this mode. -- Gabriel Genellina From j.foster.davis at gmail.com Sat Feb 23 00:03:02 2008 From: j.foster.davis at gmail.com (Jacob Davis) Date: Fri, 22 Feb 2008 21:03:02 -0800 Subject: wxPython Plot always comes to focus on redraw In-Reply-To: References: <34F026F4-EF92-4016-A10F-5BE8752B5D80@gmail.com> Message-ID: <1AA4A6FC-7F77-4E94-A018-C2F3BAC0EA28@gmail.com> Thanks for the reply. This is something that I tried. The documentation for SetFocus() says that it is for keyboard input and that Show() is supposed to show the window. I guess I was misusing the terminology. I tried your suggestion with SetFocus(), Show() and Raise(), with no joy. I think I will try the wxPython list. Thanks Jake On Feb 21, 2008, at 4:36 AM, Steve Holden wrote: > Jacob Davis wrote: >> Hi. >> >> I am using wxPython, and I have a frame that has a notebook in it. >> there are 3 pages in the notebook, 2 of which are Panels and 1 of >> which is a PlotCanvas. The data for the plot changes when I press a >> button that is in the frame, but not in the notebook (as designed). >> the button also makes the plot draw again, since the data has >> changed. >> >> The problem is that whenever I press my button, the focus of the >> notebook "view area" (as opposed to the tabs) changes focus to the >> plot. if I have multiple plots, the focus goes to that plot which >> was >> drawn last in the code. however, if I click anywhere on the panel, >> the >> page of the notebook that is supposed to be in focus is now shown in >> the "view area" of the notebook. >> >> will try to make a sample .py if anybody needs a visual, let me know >> pls. >> >> Thanks for any help! >> >> Jake > > All wxWindow objects have a SetFocus() method. I am unsure why the > system should be changing the focus (it's almost certainly something > you > are asking it to do without realizing), but the easiest way to proceed > if you can't stop the focus from changing (i.e. remove the problem) is > to call SetFocus() on the widget that you want to have the focus after > you've finished (i.e. cure the symptom). > > Or perhaps it's just that I haven't understood the problem correctly. > You probably didn't post the code because it's large (which is good). > The correct action is to pare the program down to the smallest one you > can make that demonstrates the problem, then post that. often during > this process it becomes clear what the problem is! > > It may be that your widget relationships aren't as clean as they might > be: did you produce your layout with an automated tool like wxDesigner > or BoaConstrictor, or did you hack it together by hand? > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC http://www.holdenweb.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list From http Sun Feb 24 21:27:46 2008 From: http (Paul Rubin) Date: 24 Feb 2008 18:27:46 -0800 Subject: Create multiple directories References: <5b42e76f-4b9c-4bdb-93dd-915b1bb26357@z17g2000hsg.googlegroups.com> <7xablpaihu.fsf@ruckus.brouhaha.com> Message-ID: <7x8x19g47x.fsf@ruckus.brouhaha.com> Paul Rubin writes: > fmt = "new_dir%0%d" % len(str(num)) Typo, that was supposed to say "new_dir%%0%d" ... From martin-schmitz at web.de Wed Feb 27 07:48:25 2008 From: martin-schmitz at web.de (Martin Schmitz) Date: Wed, 27 Feb 2008 13:48:25 +0100 Subject: Portable linux python install References: Message-ID: <20080227134825.379afb0e@schmitz-it-consulting.de> Am 26.02.08 schrieb "Mike M" : > I have a python application which I'd like to distribute to thousands > of machines in our server farm. Install everything you need on the oldest box available and package it with PyInstaller (http://pyinstaller.python-hosting.com/). Then you get binaries which are only linked against libc - and as it happens to be the oldest version of libc around you shouldn't have problems running the binaries with newer ones. HTH, Martin From yozara at terra.es Mon Feb 11 02:18:11 2008 From: yozara at terra.es (Zara) Date: Mon, 11 Feb 2008 08:18:11 +0100 Subject: Error on Python References: <2713302a-dade-4c5d-9eba-eb73f4f03d6f@s12g2000prg.googlegroups.com> Message-ID: On Sat, 9 Feb 2008 10:26:26 -0800 (PST), maehhheeyy wrote: >Hi, right now I'm using Python and Multicast. I have the code for >Multicast receiver on Python but I keep getting this error; > >File "", line 1, in bind >error: (10049, "Can't assign requested address") > >The error is coming from this line; >sock.bind ((MCAST_ADDR, MCAST_PORT)) > >Can anyone please help me solve this problem? This error typically arises when the address is neither the IP address of a network connection or 0.0.0.0. If you are trying to connect an IGMP socket under Windows, it may not be treated as a normal socket. You must use the corresponding setsockopt() options, and I am not sure if they are available throguh Python! Search MSDN for IGMP, or lok directly at: http://msdn2.microsoft.com/en-us/library/ms739172(VS.85).aspx If you are trying on *NIX SO, I don't know if this is applicable best regrads, Zara From steve at REMOVE-THIS-cybersource.com.au Thu Feb 7 16:25:34 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 07 Feb 2008 21:25:34 -0000 Subject: OT: Star Wars and parsecs [was Re: Why not a Python compiler?] References: <28eead2f-a40c-414b-bd3d-a941f8a851a2@d70g2000hsb.googlegroups.com> <7da40f42-f64f-4939-a0dc-d24d1ff85f2d@v4g2000hsf.googlegroups.com> <13qjktdbe76da00@corp.supernews.com> <13qmp56btnr55a4@corp.supernews.com> Message-ID: <13qmtqebm4t6979@corp.supernews.com> On Thu, 07 Feb 2008 13:44:05 -0700, Ivan Van Laningham wrote: > Gary Kurtz at SunCon 77 explained that it was a test to see if Obi-Wan > knew what he was doing; supposedly, Obi-Wan's expression indicated that > he knew Solo was feeding him shit. Why the hell would the pilot care whether the passengers knew what a parsec was? Did Concorde pilots quiz their passengers what Mach 1 means? Especially a pirate like Solo, who really only cared about one question: "can the passenger pay?". > I think Lucas didn't have a clue, myself; it's not credible that > citizens of a starfaring civilization who deliberately set out to hire a > starship wouldn't know the difference between time and distance. Occam's > razor says Lucas screwed up and doesn't want to admit it. For sure. -- Steven From ptmcg at austin.rr.com Sat Feb 16 23:06:52 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 16 Feb 2008 20:06:52 -0800 (PST) Subject: Help Parsing an HTML File References: <15f9198f-fa2a-4f4f-8f87-7402b03743e1@s13g2000prd.googlegroups.com> Message-ID: <94b9e658-eaa6-43d3-8ffe-65b49ebe3749@o10g2000hsf.googlegroups.com> On Feb 15, 3:28?pm, egonslo... at gmail.com wrote: > Hello Python Community, > > It'd be great if someone could provide guidance or sample code for > accomplishing the following: > > I have a single unicode file that has ?descriptions of hundreds of > objects. The file fairly resembles HTML-EXAMPLE pasted below. > Pyparsing was mentioned earlier, here is a sample with some annotating comments. I'm a little worried when you say the file "fairly resembles HTML- EXAMPLE." With parsers, the devil is in the details, and if you have scrambled this format - the HTML attributes are especially suspicious - then the parser will need to be cleaned up to match the real input. If the file being parsed really has proper HTML attributes (of the form ), then you could simplify the code to use the pyparsing method makeHTMLTags. But the example I wrote matches the example you posted. -- Paul # encoding=utf-8 from pyparsing import * data = """

Ros?H1-1

Ros?H2-1

... snip ... """ # define and tags CL = CaselessLiteral h1,h2,cmnt,br = \ map(Suppress, map(CL,["<%s>" % s for s in "h1 h2 comment br".split()])) h1end,h2end,cmntEnd,divEnd = \ map(Suppress, map(CL,["" % s for s in "h1 h2 comment div".split()])) # h1,h1end = makeHTMLTags("h1") # define special format for
, incl. optional quoted string "attribute" div = "<" + CL("div") + Optional(QuotedString('"'))("name") + ">" div.setParseAction( lambda toks: "name" in toks and toks.name.title() or "DIV") # define body entries h1Entry = h1 + SkipTo(h1end) + h1end h2Entry = h2 + SkipTo(h2end) + h2end comment = cmnt + SkipTo(cmntEnd) + cmntEnd divEntry = div + SkipTo(divEnd) + divEnd # just return nested tokens grammar = (OneOrMore(Group(h1Entry + (Group(h2Entry + (OneOrMore(Group(divEntry)))))))) grammar.ignore(br) grammar.ignore(comment) results = grammar.parseString(data) from pprint import pprint pprint(results.asList()) print # return nested tokens, with dict grammar = Dict(OneOrMore(Group( h1Entry + Dict(Group(h2Entry + Dict(OneOrMore(Group(divEntry)))))))) grammar.ignore(br) grammar.ignore(comment) results = grammar.parseString(data) print results.dump() Prints: [['Ros\xe9H1-1', ['Ros\xe9H2-1', ['DIV', 'Ros\xe9DIV-1'], ['Segment1', 'Ros\xe9SegmentDIV1-1'], ['Segment2', 'Ros\xe9SegmentDIV2-1'], ['Segment3', 'Ros\xe9SegmentDIV3-1']]], ['PinkH1-2', ['PinkH2-2', ['DIV', 'PinkDIV2-2'], ['Segment1', 'PinkSegmentDIV1-2']]], ['BlackH1-3', ['BlackH2-3', ['DIV', 'BlackDIV2-3'], ['Segment1', 'BlackSegmentDIV1-3']]], ['YellowH1-4', ['YellowH2-4', ['DIV', 'YellowDIV2-4'], ['Segment1', 'YellowSegmentDIV1-4'], ['Segment2', 'YellowSegmentDIV2-4']]]] [['Ros\xe9H1-1', ['Ros\xe9H2-1', ['DIV', 'Ros\xe9DIV-1'], ['Segment1', 'Ros\xe9SegmentDIV1-1'], ['Segment2', 'Ros\xe9SegmentDIV2-1'], ['Segment3', 'Ros\xe9SegmentDIV3-1']]], ['PinkH1-2', ['PinkH2-2', ['DIV', 'PinkDIV2-2'], ['Segment1', 'PinkSegmentDIV1-2']]], ['BlackH1-3', ['BlackH2-3', ['DIV', 'BlackDIV2-3'], ['Segment1', 'BlackSegmentDIV1-3']]], ['YellowH1-4', ['YellowH2-4', ['DIV', 'YellowDIV2-4'], ['Segment1', 'YellowSegmentDIV1-4'], ['Segment2', 'YellowSegmentDIV2-4']]]] - BlackH1-3: [['BlackH2-3', ['DIV', 'BlackDIV2-3'], ['Segment1', 'BlackSegmentDIV1-3']]] - BlackH2-3: [['DIV', 'BlackDIV2-3'], ['Segment1', 'BlackSegmentDIV1-3']] - DIV: BlackDIV2-3 - Segment1: BlackSegmentDIV1-3 - PinkH1-2: [['PinkH2-2', ['DIV', 'PinkDIV2-2'], ['Segment1', 'PinkSegmentDIV1-2']]] - PinkH2-2: [['DIV', 'PinkDIV2-2'], ['Segment1', 'PinkSegmentDIV1-2']] - DIV: PinkDIV2-2 - Segment1: PinkSegmentDIV1-2 - Ros?H1-1: [['Ros\xe9H2-1', ['DIV', 'Ros\xe9DIV-1'], ['Segment1', 'Ros \xe9SegmentDIV1-1'], ['Segment2', 'Ros\xe9SegmentDIV2-1'], ['Segment3', 'Ros\xe9SegmentDIV3-1']]] - Ros?H2-1: [['DIV', 'Ros\xe9DIV-1'], ['Segment1', 'Ros \xe9SegmentDIV1-1'], ['Segment2', 'Ros\xe9SegmentDIV2-1'], ['Segment3', 'Ros\xe9SegmentDIV3-1']] - DIV: Ros?DIV-1 - Segment1: Ros?SegmentDIV1-1 - Segment2: Ros?SegmentDIV2-1 - Segment3: Ros?SegmentDIV3-1 - YellowH1-4: [['YellowH2-4', ['DIV', 'YellowDIV2-4'], ['Segment1', 'YellowSegmentDIV1-4'], ['Segment2', 'YellowSegmentDIV2-4']]] - YellowH2-4: [['DIV', 'YellowDIV2-4'], ['Segment1', 'YellowSegmentDIV1-4'], ['Segment2', 'YellowSegmentDIV2-4']] - DIV: YellowDIV2-4 - Segment1: YellowSegmentDIV1-4 - Segment2: YellowSegmentDIV2-4 From luismgz at gmail.com Sun Feb 24 00:06:08 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M._Gonz=E1lez?=) Date: Sat, 23 Feb 2008 21:06:08 -0800 (PST) Subject: Seeing "locals()" from imported function Message-ID: <9fbdbc65-1c3e-4591-8113-d0cba502c08f@p73g2000hsd.googlegroups.com> I apologize for this very basic question, but I can't understand how this works... I want to import a function from module B into my main script A, so this function can see and use the locals from A. For example: def auto(): urls = ['/', 'index'] for k,v in __main__.locals().items(): # these "locals" are the ones of the main script if isinstance(v,type) and k != 'index': urls.append('/%s' %k) urls.append(k) return tuple(urls) Of course this doesn't work... Any hint? Luis From paddy3118 at googlemail.com Sat Feb 9 01:13:05 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 8 Feb 2008 22:13:05 -0800 (PST) Subject: sort functions in python References: Message-ID: <70e4bf36-f8d6-46b8-92f1-a4a9eb050432@i7g2000prf.googlegroups.com> On 9 Feb, 01:00, t3chn0n3rd wrote: > Do you think it is relatively easy to write sort algorithms such as > the common Bubble sort in Python as compared to other high level > programming langauges Hi, >From a quick google, you could compare the sources here: http://www.daniweb.com/code/snippet452.html with those from here: http://cg.scs.carleton.ca/~morin/misc/sortalg/ (It seems that sort routines are a favourite for showing off Java applet capability). - Paddy. P.S. I also found this absolute gem: The intelligent design sort, "works outside of time .." http://www.dangermouse.net/esoteric/intelligentdesignsort.html :-) From spgarg04 at gmail.com Sun Feb 17 11:09:54 2008 From: spgarg04 at gmail.com (Surya Prakash Garg) Date: Sun, 17 Feb 2008 21:39:54 +0530 Subject: Animated GIF in Tkinter Message-ID: <5a22a1610802170809u67f691a3w9072d255037513e9@mail.gmail.com> Hello, I have created a frame in which i want to display an animated progressbar in a canvas. I use PhotoImage function of PIL. But it doesn't display the animated gif code looks like this self.imgobj = PhotoImage(file=imgpath) self.c = Canvas(self.frame2, bg='white',width=64,height=310) self.c.place(x=x0,y=y0) self.c.create_image(x0,y0,image=self.imgobj,anchor=NW) did a lot of googling on it. but nothing found. I can't switch to wxPython. Please help me. thanks -- Surya Prakash Garg Bangalore +919886801350 -------------- next part -------------- An HTML attachment was scrubbed... URL: From j.foster.davis at gmail.com Sat Feb 23 00:01:10 2008 From: j.foster.davis at gmail.com (Jacob Davis) Date: Fri, 22 Feb 2008 21:01:10 -0800 Subject: wxPython Plot always comes to focus on redraw In-Reply-To: <5c220d1d-f820-4024-976e-1b172f936b08@t66g2000hsf.googlegroups.com> References: <5c220d1d-f820-4024-976e-1b172f936b08@t66g2000hsf.googlegroups.com> Message-ID: Thanks for the reply. The parent is a notebook. (the Plotcanvas is a page in the notebook) I tried to make the page of the notebook a panel, and then make the PlotCanvas a child of this panel, but the Plot would not show up when drawn. I may have time to make a mini program to duplicate the error in the future... On Feb 21, 2008, at 6:14 AM, Mike Driscoll wrote: > On Feb 21, 2:57 am, Jacob Davis wrote: >> Hi. >> >> I am using wxPython, and I have a frame that has a notebook in it. >> there are 3 pages in the notebook, 2 of which are Panels and 1 of >> which is a PlotCanvas. The data for the plot changes when I press a >> button that is in the frame, but not in the notebook (as designed). >> the button also makes the plot draw again, since the data has >> changed. >> >> The problem is that whenever I press my button, the focus of the >> notebook "view area" (as opposed to the tabs) changes focus to the >> plot. if I have multiple plots, the focus goes to that plot which >> was >> drawn last in the code. however, if I click anywhere on the panel, >> the >> page of the notebook that is supposed to be in focus is now shown in >> the "view area" of the notebook. >> >> will try to make a sample .py if anybody needs a visual, let me know >> pls. >> >> Thanks for any help! >> >> Jake > > Just a show in the dark, but is the plotcanvas object's parent a frame > or a panel? If it's the frame, than that's probably what the problem > is. > > You may want to post to the wxPython list where you'll get wx geeks to > answer your question and you can learn a lot from them too. Here's a > link where you can sign up: http://wxpython.org/maillist.php > > Mike > > -- > http://mail.python.org/mailman/listinfo/python-list From dhwild at talktalk.net Tue Feb 19 17:33:48 2008 From: dhwild at talktalk.net (David H Wild) Date: Tue, 19 Feb 2008 22:33:48 +0000 (GMT) Subject: Encrypting a short string? References: <61o2t0F205p5fU1@mid.individual.net> <13rmlec867jcnc2@corp.supernews.com> Message-ID: <47bb5a0c$0$1344$834e42db@reader.greatnowhere.com> In article <13rmlec867jcnc2 at corp.supernews.com>, Steven D'Aprano wrote: > > I really don't recommend the ROT13 cipher, as this is extremely easy to > > crack. Most grade school kids could break this one in seconds. ;-) > I think you missed the point. Any recommendation to use ROT13 is likely > to be a joke. A recommendation to use Triple ROT13 is *absolutely* a > joke. ROT13 does have a legitimate use, but it's not as a cypher. It is really the equivalent of the newspaper quiz where the answers are upside down at the bottom of the page. By doing this you stop seeing the answers too early. -- David Wild using RISC OS on broadband www.davidhwild.me.uk From qwe at ngi.it Sun Feb 10 11:31:59 2008 From: qwe at ngi.it (MASI) Date: Sun, 10 Feb 2008 17:31:59 +0100 Subject: Tkinter equiv for setPalette References: <47aeda20$0$2988$ba620e4c@news.skynet.be> Message-ID: Il Sun, 10 Feb 2008 12:03:59 +0100, Helmut Jarausch ha scritto: > Hi, > > I am to convert an old Perl-Tk script to Python. > It starts by > my $MW= new MainWindow; > $MW->setPalette(background => 'AntiqueWhite1', foreground => 'blue'); > > Is there an equivalent for Tkinter? How can I set default colors for > background and foreground for the whole application (root window and its > children) > > Many thanks for a hint, > Helmut. You have two options: 1) put your preference in a file eg file 'tk_option': *foreground: blue *background: green *Entry*background: red and read it root = Tkinter.Tk() root.option_readfile('tk_option') 2) in your program whit option_add eg root = Tkinter.Tk() root.option_add('*foreground', 'blue') root.option_add('*background', 'green') root.option_add('*Entry*background', 'red') From toddw at activestate.com Thu Feb 7 12:25:44 2008 From: toddw at activestate.com (Todd Whiteman) Date: Thu, 07 Feb 2008 09:25:44 -0800 Subject: Paramiko SFTP autologon using id_dsa.pub In-Reply-To: <5491b0ed-946a-4b5b-8f2a-75e900df0be9@e23g2000prf.googlegroups.com> References: <5491b0ed-946a-4b5b-8f2a-75e900df0be9@e23g2000prf.googlegroups.com> Message-ID: <47AB3F18.3080308@activestate.com> Mike Hjorleifsson wrote: > I wrote a lil module using paramiko's module to send a file via > sftp.. it works great using the username and password. > I would prefer to use id_dsa.pub to have an autologon and not save > the > password anywhere on the disk.. I cant find a good example of this. > Can anyone help ? Hi Mike, If you download the Paramiko zip archive: http://www.lag.net/paramiko/download/paramiko-1.7.2.zip You can find examples of loading and using public/private keys for automated logins in the code under the "demos" sub folder. Cheers, Todd From ggpolo at gmail.com Sun Feb 3 13:55:29 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Sun, 3 Feb 2008 16:55:29 -0200 Subject: Python GUI toolkit In-Reply-To: References: <1s8h75-vbf.ln1@strongwill.g2ctech> Message-ID: 2008/2/3, Christian Heimes : > Jorge Godoy wrote: > > Qt is a the best choice, IMHO. Nice support, free if you write free > > software, very nice API, nice tools to develop with and the best looking > > widget system for *nix and mobile phones. > > > PyQt4 forces you to either release your software under GPL or buy a > license. Qt3 and Qt4 allow many more open source licenses but PyQt's > license module doesn't. > PyQt follows same licensing as Qt, so what licenses does Qt4 supports besides GPL and Qt commercial license ? > > Christian > > > PS: I also prefer Qt4 over wx and GTK. :) > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From steve at holdenweb.com Sun Feb 24 12:46:23 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 24 Feb 2008 12:46:23 -0500 Subject: How about adding rational fraction to Python? In-Reply-To: <97f30679-483d-4751-9a6e-0858b36eb426@d4g2000prg.googlegroups.com> References: <13rde22ktgpu532@corp.supernews.com> <26641b5f-d6cb-45a6-8736-7d130d1a5aee@u10g2000prn.googlegroups.com> <13a4316e-3ce7-4b3e-b418-6efb988a8845@q78g2000hsh.googlegroups.com> <676ca28c-b471-41c8-8661-fcd2ea8c23f0@i12g2000prf.googlegroups.com> <74b95b3b-1d6a-42a6-b55d-e77a868b1ffe@64g2000hsw.googlegroups.com> <70ecaf16-7308-455f-9048-730b2b2f9f2f@p43g2000hsc.googlegroups.com> <13rf9tvbkt66r2a@corp.supernews.com> <198927a7-9478-42b3-a972-82049f0130ac@u10g2000prn.googlegroups.com> <1bc9bba7-dc7f-4cfe-8e1c-fa5901c9f556@n77g2000hse.googlegroups.com> <97f30679-483d-4751-9a6e-0858b36eb426@d4g2000prg.googlegroups.com> Message-ID: Lie wrote: > On Feb 18, 1:25 pm, Carl Banks wrote: >> On Feb 17, 1:45 pm, Lie wrote: >> >>>> Any iteration with repeated divisions and additions can thus run the >>>> denominators up. This sort of calculation is pretty common (examples: >>>> compound interest, numerical integration). >>> Wrong. Addition and subtraction would only grow the denominator up to >>> a certain limit >> I said repeated additions and divisions. > > Repeated Addition and subtraction can't make fractions grow > infinitely, only multiplication and division could. > On what basis is this claim made? (n1/d1) + (n2/d2) = ((n1*d2) + (n2*d1)) / (d1*d2) If d1 and d2 are mutually prime (have no common factors) then it is impossible to reduce the resulting fraction further in the general case (where n1 = n2 = 1, for example). >> Anyways, addition and subtraction can increase the denominator a lot >> if for some reason you are inputing numbers with many different >> denominators. > > Up to a certain limit. After you reached the limit, the fraction would > always be simplifyable. > Where does this magical "limit" appear from? > If the input numerator and denominator have a defined limit, repeated > addition and subtraction to another fraction will also have a defined > limit. Well I suppose is you limit the input denominators to n then you have a guarantee that the output denominators won't exceed n!, but that seems like a pretty poor guarantee to me. Am I wrong here? You seem to be putting out unsupportable assertions. Please justify them or stop making them. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From diljeet_kr at yahoo.com Mon Feb 25 22:40:06 2008 From: diljeet_kr at yahoo.com (diljeet kaur) Date: Mon, 25 Feb 2008 19:40:06 -0800 (PST) Subject: buliding log files Message-ID: <361454.10723.qm@web52802.mail.re2.yahoo.com> hi im working on pyqt environment i want to know how to take log or how to build log files of the output --------------------------------- Looking for last minute shopping deals? Find them fast with Yahoo! Search. -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Fri Feb 22 03:45:59 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 22 Feb 2008 00:45:59 -0800 (PST) Subject: Return value of an assignment statement? References: <6d945394-739e-4c47-ad71-faaab8f9d566@34g2000hsz.googlegroups.com> <5ffc7183-6e32-42d1-b9a1-a7514cd085c3@i7g2000prf.googlegroups.com> Message-ID: On Feb 21, 6:52 pm, Steve Holden wrote: > mrstephengross wrote: > >> What you can't do (that I really miss) is have a tree of assign-and-test > >> expressions: > >> import re > >> pat = re.compile('some pattern') > >> if m = pat.match(some_string): > >> do_something(m) > > > Yep, this is exactly what I am (was) trying to do. Oh well.... Any > > clever ideas on this front? > > The syntax is the way it is precisely to discourage that kind of clever > idea. Don't be ridiculous. Assignment operators are maybe one of the worst things in existence, but this particular use case (running a sequence of tests like the above) is perfectly useful and good. Some Pythonistas will swear to their grave and back that should be done by factoring out the tests into a list and iterating over it, and NO OTHER WAY WHATSOEVER, but I don't buy it. That's a lot of boilerplate--the very thing Python is normally so good at minimizing-- when it might not be needed. It would be the right thing for a complex, pluggable, customizable input filter; but is rarely a better solution for a simple text processing script. Quick, at a glance, which code snippet will you understand faster (pretend you know Perl): if (/name=(.*)/) { $name = chop(\1); } elsif (/id=(.*)/) { $id = chop(\1); } elsif (/phone=(.*)/) { $phone = chop(\1); } vs. def set_phone_number(m): phone = m.group(1).strip() def set_id(m): id = m.group(1).strip() def set_name(m): name = m.group(1).strip() _line_tests = [ (r"phone=(.*)", set_phone_number), (r"name=(.*)", set_name), (r"id=(.*)", set_id), ] for pattern,func in _line_tests: m = re.match(pattern,line) if m: func(m) At this small scale, and probably at much larger scales too, the Perl example blows the Python example out of the water in terms of readability. And that's counting Perl's inherent unreadableness. If it were a priority, Python could support this set-and-test idiom, and without an assignment operator. (Notice Perl doesn't use assignment operator here.) For example, a syntax like this (where the scope of m is local to the if-condition and the body of the if- statement: if m where m = re.match(r"name=(.*)",line): name = m.group(1).strip() elif m where m = re.match(r"id=(.*)",line): id = m.group(1).strip() elif m where m = re.match(r"phone=(.*)",line): phone = m.group(1).strip() This won't happen because the set-and-test idiom is relatively minor and not deemed worthy of syntax support. But if it were there, there'd really be nothing clever about it. Carl Banks From luismgz at gmail.com Fri Feb 15 07:22:37 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M._Gonz=E1lez?=) Date: Fri, 15 Feb 2008 04:22:37 -0800 (PST) Subject: Is there a way to use .NET DLL from Python References: <85706ba0-8c24-4324-9a79-98c97fc802db@e4g2000hsg.googlegroups.com> <6c2845aa-aec5-4b75-852a-551b9cd1d6ab@f10g2000hsf.googlegroups.com> <5845a12f-41dd-4bb3-8684-483e93f55c5f@e25g2000prg.googlegroups.com> <5cbdc3cf-cb84-49e5-b746-2eca0feeb97d@i7g2000prf.googlegroups.com>, <2298129a-3ca5-41f9-86ed-28805397fd54@f47g2000hsd.googlegroups.com> <2a883225-7622-4dc4-be85-daf4ff3cfe6c@u10g2000prn.googlegroups.com> Message-ID: <5f3324a6-3e62-4012-aac3-513169b6e800@e6g2000prf.googlegroups.com> On Feb 14, 6:26 pm, Fuzzyman wrote: > On Feb 13, 6:58 pm, "Luis M. Gonz?lez" wrote: > > > > > On 13 feb, 00:26, Dino Viehland wrote: > > > > >> Oh, I know what you mean. > > > >> But that was exactly the reason for having a .DLLs folder, isn't it? > > > >> When you place an assembly into this folder, you avoid having to write > > > >> this boilerplate code, and simply import the assembly as you would > > > >> with a normal python module. At least, that?s how it worked in > > > >> previous versions... > > > >No. You have always had to add references to assemblies before being > > > >able to use the namespaces they contain. You even have to do this with > > > >C# in Visual Studio. > > > > This *should* work in bothIronPython1.x and IronPyton 2.0 - the catch though is that it's implemented in the default site.py we ship with. So if you do the usual thing and use CPython's Lib directory you'll lose this feature w/o copying it over. > > > Sorry Dino, I don't understand... > > What does Cpython's Lib have to do with it? > > If you have the CPython standard library in your IRONPYTHONPATH, then > when IronPython does it's normal 'import site' on startup the CPython > one will be used instead of the default IronPython one... > > Michael Foordhttp://www.manning.com/foord I see. Thank you! Luis From SaqibQureshi at gmail.com Thu Feb 21 01:47:02 2008 From: SaqibQureshi at gmail.com (Saqib Mehmood) Date: Wed, 20 Feb 2008 22:47:02 -0800 (PST) Subject: ENMAC Mobile Phones, iPods EQ100 www.enmac.com.hk References: <1bd560ad-b579-49e5-abeb-2111d2843aa6@e25g2000prg.googlegroups.com> Message-ID: <0522f5b5-8dad-488d-b6e7-302a63b9d397@e60g2000hsh.googlegroups.com> On Jan 24, 1:43 pm, Farooq wrote: > www.enmac.com.hk > GSM Mobile Phones, Digital iPods, Digital Clocks, Digital Pens, > Digital Quran. Enjoy these products with Islamic Features (Complete > Holy Quran with Text and Audio, Tafaseer books, Ahadees Books, Daily > Supplications, Universal Qibla Direction, Prayer Timing and much more) > visit our website for more information. from where I can get the prices for there products. Regards, Saqib From bots.dce at gmail.com Sat Feb 9 03:33:29 2008 From: bots.dce at gmail.com (bots) Date: Sat, 9 Feb 2008 00:33:29 -0800 (PST) Subject: troika 2008 Message-ID: <4d87fb22-bab7-4911-8807-f684efd62b03@v67g2000hse.googlegroups.com> Hello programmers, IEEE Student branch, Delhi College of Engineering invites you to be a part of its much awaited technical fest TROIKA '08 Get ready to enter the battle where your analytical skills and mental acumen are tested to their maximum, where time runs fast and beating the odds is a dire necessity. Welcome to the BITS, BYTES & BOTS saga, a battlefield where the brainstormers fight to rule the binary world. Code hard and fast and you might be the next king in town. Exciting cash prizes to be won!!! BITS: On-site programming The event is held on a two-tier basis. The Prelims consist of an elimination round from which the top coders will be selected for the final programming challenge. Whilst logic might be the strongest, the time slips away fast. Grab the chance to make it a win of a lifetime. Registration has started for the event. Event date: 19th Feb, 2008 For details see www.troika.dcetech.com Queries & Registration: bits.dce at gmail.com BYTES: Overnight Online Programming Contest The event consists of a single round of programming contest in which the participants code among the toughest of competitors. But if your logic is right, you may outrun the best of the best. Be a part of BYTES and let the race begin. Registrations open. Event date: 16th Feb, 2008 For details see www.troika.dcetech.com Queries & Registration: bytes.dce at gmail.com BOTS: Virtual-Bot Programming Contest Based on the theme of the Pirates of the Caribbean, in this programming contest you develop a code to run a virtual bot. The task is to find a path to move objects to their destinations avoiding all possible obstacles and hindrances. Sure the going is tough and the enemies are strong, but get your moves right and you will be surprised with the rewards that come your way. Problem statement released. Event date: 20th Feb, 2008 For details see www.troika.dcetech.com Queries & Registration: bots.dce at gmail.com From gagsl-py2 at yahoo.com.ar Tue Feb 26 00:01:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 26 Feb 2008 03:01:33 -0200 Subject: Odd behaviour of *.pth files and Apache References: <20080221135525.e4f59094.darcy@druid.net> <20080223095245.7c6af2e1.darcy@druid.net> Message-ID: En Sat, 23 Feb 2008 12:52:45 -0200, D'Arcy J.M. Cain escribi?: > On Thu, 21 Feb 2008 13:55:25 -0500 > "D'Arcy J.M. Cain" wrote: >> I tried searching the archives for information on this but nothing >> seemed to be germane. I am running Python sripts as CGI under Apache >> and I have a .pth file in site-packages that includes directory that >> has another .pth in it. Sometimes it picks up the paths in the >> second .pth and sometimes it does not. It always seems to work if I am >> working in a location not in the ServerRoot but if I use the main site >> it does not pick up the directories in the included .pth. > > I have more information now. It seems that it recurses the .pth files > it finds in PYTHONPATH but not for directories found in the .pth files > in site-packages. Is this expected behaviour? The documentation > suggests that it should pick up both. If a .pth file contains a valid directory, it is added to sys.path but it's not searched for additional .pth files. From http://docs.python.org/lib/module-site.html "A path configuration file is a file whose name has the form package.pth AND EXISTS IN ONE OF THE FOUR DIRECTORIES MENTIONED ABOVE" (emphasis by me) (the four directories being .../lib/python2.5/site-packages, site-python, etc.) (Mmm, what the 2.5 docs say is not exactly the same as the actual code in site.py, and the version in http://docs.python.org/dev/library/site.html is not the same as the svn version of site.py... anyway, directories added by mean of .pth files are not recursively searched for more .pth files) -- Gabriel Genellina From darcy at druid.net Thu Feb 28 11:22:43 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Thu, 28 Feb 2008 11:22:43 -0500 Subject: How about adding rational fraction to Python? In-Reply-To: References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <7x63wbez2b.fsf@ruckus.brouhaha.com> <13sc3ccds5ap5a9@corp.supernews.com> <13scs8k1kh9nk81@corp.supernews.com> Message-ID: <20080228112243.bd752e99.darcy@druid.net> On Thu, 28 Feb 2008 06:10:13 -0800 (PST) Carl Banks wrote: > On Feb 28, 3:30 am, Dennis Lee Bieber wrote: > > Automatic conversions, okay... but converting a result when all > > inputs are of one time, NO... > > People, this is so cognitive dissonance it's not even funny. I'll say. > There is absolutely nothing obvious about 1/2 returning a number that > isn't at least approximately equal to one half. There is nothing self- > evident about operations maintaining types. Not obvious to you. You are using subjective perception as if it was a law of nature. If "obvious" was the criteria then I would argue that the only proper result of integer division is (int, int). Give me the result and the remainder and let me figure it out. > You people can't tell the difference between "obvious" and "learned > conventions that came about because in limitations in the hardware at > the time". Nobody would have come up with a silly rule like "x op y > must always have the same type as x and y" if computer hardware had > been up to the task when these languages were created. What makes you say they weren't? Calculating machines that handled floating point are older than Python by far. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From george.sakkis at gmail.com Tue Feb 5 22:26:39 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 5 Feb 2008 19:26:39 -0800 (PST) Subject: What is the most simple, quicket, yet most powerful python Web-Framework? References: <5d022604-289d-4d4c-bd9a-286435cf77a6@d21g2000prf.googlegroups.com> Message-ID: <6695d77a-6b2b-44a0-8250-c7693a66d19c@m34g2000hsb.googlegroups.com> xkenneth wrote: > For the DB backend I'm planning on using ZODB. ZODB is actually > quite amazing, and after using it, I honestly can't think of a > reason for using a SQL database. Well, one reason is that this probably rules out most of your options since most web frameworks include (or integrate with) an ORM layer, which in turn talks to a (relational) database. If you're sold on ZODB, you may want to evaluate Grok [1], a Web framework built on top of Zope 3 that doesn't seem to require knowledge of Zope internals. HTH, George [1] http://grok.zope.org/ From miki.tebeka at gmail.com Thu Feb 21 08:41:58 2008 From: miki.tebeka at gmail.com (Miki) Date: Thu, 21 Feb 2008 05:41:58 -0800 (PST) Subject: Tkinter OSX and "lift" References: <47BD7D5F.1060205@codebykevin.com> Message-ID: <29454149-0dfa-4092-a625-0955dbc6ca5d@e10g2000prf.googlegroups.com> Hello Kevin, > Tk.lift doesn't seem to work on OSX (Python 2.5.1). >> If you click on the PythonLauncher application that runs in your dock >> when this script is executed, the window comes into focus fine. You're right, but I want to window to be initially in focus (without the user clicking on the python launcher icon). All the best, -- Miki http://pythonwise.blogspot.com From PieSquared at gmail.com Sun Feb 17 13:32:40 2008 From: PieSquared at gmail.com (Pie Squared) Date: Sun, 17 Feb 2008 10:32:40 -0800 (PST) Subject: Python Memory Manager Message-ID: I've been looking at the Python source code recently, more specifically trying to figure out how it's garbage collector works. I've gathered that it uses refcounting as well as some cycle-detection algorithms, but I haven't been able to figure out some other things. Does Python actually have a single 'heap' where all the data is stored? Because PyObject_HEAD seemed to imply to me it was just a linked list of objects, although perhaps I didnt understand this correctly. Also, if it does, how does it deal with memory segmentation? This question bothers me because I've been trying to implement a moving garbage collector, and am not sure how to deal with updating all program pointers to objects on the heap, and thought perhaps an answer to this question would give me some ideas. (Also, if you know any resources for things like this, I'd be grateful for links/names) Thanks in advance, Pie Squared From steve at holdenweb.com Thu Feb 21 19:16:15 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 21 Feb 2008 19:16:15 -0500 Subject: Return value of an assignment statement? In-Reply-To: References: <6d945394-739e-4c47-ad71-faaab8f9d566@34g2000hsz.googlegroups.com> <835a4fc1-f62a-4141-bca4-4e4f52519466@s37g2000prg.googlegroups.com> <5sudnTSXrZY0aCDanZ2dnUVZ_rKtnZ2d@comcast.com> <67ff8198-1d7d-4690-a9b6-42ebab2e642f@p73g2000hsd.googlegroups.com> Message-ID: Jeff Schwab wrote: > bruno.desthuilliers at gmail.com wrote: [...] >> Now there's no reason to feel nervous about this. All you have to >> remember is that Python never copy anything unless explicitely asked >> for. > > It's not that simple. After a statement like: > > a = b > > Whether a and b denote the same object depends on what kind of object b > represented in the first place. Surely this is exactly wrong. Is there a single example you can think of where a = b assert a is b, "Oops!" would raise and exception? Perhaps you meant to use an augmented assignment operation? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From rw at smsnet.pl Fri Feb 22 13:12:09 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Fri, 22 Feb 2008 19:12:09 +0100 Subject: Tkinter Menu Item Activation References: <71e3a86d-f344-4819-8db9-28710d0fdaf4@z17g2000hsg.googlegroups.com> Message-ID: <87tzk0rhc6.fsf@merkury.smsnet.pl> MartinRinehart at gmail.com writes: > Tkinter definitely deserves more respect! I'm making rapid progress > and it looks good. > > But am stuck on this: I want the File/Save state to change from > disabled to enabled, depending on whether or not there is something to > save (Text modified). Google returns results in every language except > Python. > Sub problems: how to change state of menu item? how to detect changes > in Text widget? > > Help appreciated. State of menu items can be changed like this: import Tkinter as Tk def hello(): if mfile.entrycget(2, 'state') == 'disabled': state = 'normal' else: state = 'disabled' mfile.entryconfigure(2, state=state) root = Tk.Tk() menubar = Tk.Menu(root) mfile = Tk.Menu(menubar) mfile.add_command(label="Open", command=hello) mfile.add_command(label="Save", command=hello) menubar.add_cascade(label='File', menu=mfile) root.config(menu=menubar) root.mainloop() But I think that you should read this: http://effbot.org/zone/vroom.htm HTH, Rob From stefan_ml at behnel.de Sun Feb 17 01:54:36 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 17 Feb 2008 07:54:36 +0100 Subject: Validating cElementTrees with lxml In-Reply-To: References: Message-ID: <47B7DA2C.8080704@behnel.de> Hi, Ryan K wrote: > If I have a cElementTree.ElementTree (or the one from the Standard > Library), can I use lxml's validation features on it since it > implements the same ElementTree API? Not directly. lxml and cElementTree use different tree models internally, so you can't just apply C-implemented features of one to the other. Any reason you can't just use lxml /instead/ of cElementTree? In case you really want to combine both: to validate the tree, you only need to create an lxml tree from your ElementTree in a one-way operation, which is easy, as this can be done through the (identical) API. Just create a new lxml Element and then traverse the ElementTree recursively, create a new SubElement for each child you find, and set its text, tail and attrib properties. Something like this might work (though untested): class TreeMigrator(object): def __init__(ET_impl_from, ET_impl_to): self.Element = ET_impl_to.Element self.SubElement = ET_impl_to.SubElement def copyChildren(self, from_parent, to_parent): for from_child in from_parent: tag = from_child.tag if not isinstance(tag, basestring): # skip Comments etc. continue to_child = self.SubElement( to_parent, tag, **from_child.attrib) to_child.text = child.text to_child.tail = child.tail self.copyChildren(from_child, to_child) def __call__(self, from_root): tag = from_root.tag to_root = self.Element(tag, **from_root.attrib) to_root.text = from_root.text to_root.tail = from_root.tail if isinstance(tag, basestring): # skip Comments etc. self.copyChildren(from_root, to_root) return to_root Feel free to finish it up and send it back to the list. :) Stefan From mensanator at aol.com Wed Feb 13 14:11:13 2008 From: mensanator at aol.com (mensanator at aol.com) Date: Wed, 13 Feb 2008 11:11:13 -0800 (PST) Subject: Regular Expression for Prime Numbers (or How I came to fail at them, and love the bomb) References: <85ca4615-c51f-4aab-b400-f3f80056faec@l32g2000hse.googlegroups.com> Message-ID: On Feb 13, 12:53?pm, Carsten Haese wrote: > On Wed, 2008-02-13 at 10:40 -0800, mensana... at aol.com wrote: > > But why doesn't it work when you make that change? > > I can't answer that question, because it *does* work when you make that > change. Well, the OP said the function was returning None which meant no match which implies None means composite for the given example 2. If None was supposed to mean prime, then why would returing None for 2 be a problem? But isn't this kind of silly? ## 3 None ## 4 <_sre.SRE_Match object at 0x011761A0> ## 5 None ## 6 <_sre.SRE_Match object at 0x011761A0> ## 7 None ## 8 <_sre.SRE_Match object at 0x011761A0> ## 9 <_sre.SRE_Match object at 0x011761A0> ## 10 <_sre.SRE_Match object at 0x011761A0> ## 11 None ## 12 <_sre.SRE_Match object at 0x011761A0> ## 13 None ## 14 <_sre.SRE_Match object at 0x011761A0> ## 15 <_sre.SRE_Match object at 0x011761A0> ## 16 <_sre.SRE_Match object at 0x011761A0> ## 17 None ## 18 <_sre.SRE_Match object at 0x011761A0> ## 19 None > > -- > Carsten Haesehttp://informixdb.sourceforge.net From paul.hermeneutic at gmail.com Sat Feb 16 11:59:18 2008 From: paul.hermeneutic at gmail.com (Paul Watson) Date: Sat, 16 Feb 2008 10:59:18 -0600 Subject: SOAP strategies Message-ID: <1203181157.2649.11.camel@localhost.localdomain> What are the reasonable current day choices and best bets for the future when doing SOAP programming in Python? SOAP batteries do not appear to be in the standard Python distribution. Most of the SOAP related information I have been able to find on the web is from 2001-2002. I am not sure if some packages are still maintained. Most of this is old news. http://soapy.sourceforge.net/ http://pywebsvcs.sourceforge.net/ (SOAPpy) and what is the relation of this to ZSI http://www.intertwingly.net/stories/2002/12/20/sbe.html http://www.ibm.com/developerworks/library/ws-pyth5/ http://www.opensourcetutorials.com/tutorials/Server-Side-Coding/Python/python-soap-libraries/page1.html http://www.gossamer-threads.com/lists/python/python/619251 This is current, but is this a long term strategy or a short term tactic? From j.foster.davis at gmail.com Thu Feb 21 02:01:42 2008 From: j.foster.davis at gmail.com (Jacob Davis) Date: Wed, 20 Feb 2008 23:01:42 -0800 Subject: usenet problem Message-ID: Hi. I am a newbie to usenet. I am using mac and have downloaded a free usenet client, "MT-NewsWatcher". I put in comp.lang.python but it says that it cannot get the address of the news server host. My config says it is trying on port 119. Thanks for any help. Jake From xnews2 at fredp.lautre.net Tue Feb 19 12:41:03 2008 From: xnews2 at fredp.lautre.net (Fred Pacquier) Date: 19 Feb 2008 17:41:03 GMT Subject: ANN: Phatch = PHoto bATCH processor and renamer based on PIL References: <15f9eaeb-8d02-4090-922e-97a65c20fe51@e23g2000prf.googlegroups.com> Message-ID: Steve Holden said : > Perhaps you could put a link to the source on the Windows instalL page? > I don't mind being a second-class citizen, but it's annoying to have to > jump around like that. I'm interested too, and was also wondering if Phatch is as full-featured unders Windows as under Linux, specifically the EXIF/IPTC functions made available through pyexiv2 : exiv2 itself seems to discriminate between the two, the Windows package only has the executable, not the library. -- YAFAP : http://www.multimania.com/fredp/ From parvini_navid at yahoo.com Sun Feb 3 08:04:14 2008 From: parvini_navid at yahoo.com (Navid Parvini) Date: Sun, 3 Feb 2008 05:04:14 -0800 (PST) Subject: scope Message-ID: <438712.29654.qm@web54505.mail.re2.yahoo.com> Dear All, I have the following two methods in a module. I cannot put them in a class, as the code is a complicated one. def a(num): found = num in Numlist print found def b(): scop = {} scop['Numlist'] = [1,2,3] scop['a'] = a exec("a(3)",scop) How can I access the "Numlist" inside the method a, without using classes or defining Numlist as GLOBAL? I prefer using scops in this problem. Is there a way? Thank you very much, Navid --------------------------------- Looking for last minute shopping deals? Find them fast with Yahoo! Search. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bignose+hates-spam at benfinney.id.au Wed Feb 20 20:09:45 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 21 Feb 2008 12:09:45 +1100 Subject: The big shots References: <89d15587-e8de-444c-b240-4a10305146e0@e23g2000prf.googlegroups.com> <3c035ede-d98b-4adc-bde4-5a918bd04dd8@h25g2000hsf.googlegroups.com> <586b3c9c-6b8b-4fce-9307-4984b857276a@s37g2000prg.googlegroups.com> <87ir0jgor9.fsf@benfinney.id.au> <4f3c8b44-9ba6-4901-a0fe-4f2de0ce0b2b@q70g2000hsb.googlegroups.com> Message-ID: <87ejb7glnq.fsf@benfinney.id.au> castironpi at gmail.com writes: > On Feb 20, 6:02?pm, Ben Finney > wrote: > > For what it's worth, I've found none of your threads in the last > > few weeks to make much sense at all, because of unclear and > > incoherent writing. On that basis, I dismiss them before trying to > > re-read them, because I don't want to spend my time trying to find > > sense in them that may not be there at all. > > How do I "bake" this idea? [loads of further verbiage apparently > nothing to do with what Ben Finney wrote] Here's another example of the above point. I've no idea what the context is supposed to be of all the stuff you just wrote in your message. It's also written in a fractured style that makes it very difficult to follow. Hence, I tune out. > Are further problems a) miscommunication or b) absence of content? > If Holden and Genellina don't follow, that's a strong sign that the > structure of my proposals is really bad, even if there's a good > thing behind it. You just have to solve (a) before you solve (b), > which makes devoting resources to (a) a little preliminary. Agreed. I'll wait until you have better results from improving communication before I devote further resources to your messages. -- \ "It's a good thing we have gravity or else when birds died | `\ they'd just stay right up there. Hunters would be all | _o__) confused." -- Steven Wright | Ben Finney From gherron at islandtraining.com Mon Feb 25 11:49:48 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 25 Feb 2008 08:49:48 -0800 Subject: String compare question In-Reply-To: <496954360802250836u162eeb49tfac382c6ef2f96a7@mail.gmail.com> References: <496954360802250836u162eeb49tfac382c6ef2f96a7@mail.gmail.com> Message-ID: <47C2F1AC.7030004@islandtraining.com> Robert Dailey wrote: > Hi, > > Currently I have the following code: > > > ignored_dirs = ( > r".\boost\include" > ) You expect this is creating a tuple (or so I see from your "in" test in the following code), but in fact the parenthesis do *not* make a tuple. If you look at ignored_dirs, you'll find it's just a string. It's the presence of commas that signam a tuple. You need ignored_dirs = ( r".\boost\include", # It's that comma that makes this a tuple. ) > > if __name__ == "__main__": > # Walk the directory tree rooted at 'source' > for root, dirs, files in os.walk( source ): > if root not in ignored_dirs: > CopyFiles( root, files, ".dll" ) > else: > print root > > > Specifically take a look at the if condition checking if a string is > inside of ignored_dirs. Of course this will only do substring > searches, however I want to perform an exact match on this string. Is > there anyway of doing this? Thanks. From grante at visi.com Tue Feb 19 23:29:42 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 20 Feb 2008 04:29:42 -0000 Subject: The big shots References: <89d15587-e8de-444c-b240-4a10305146e0@e23g2000prf.googlegroups.com> <7xmypx61z6.fsf@ruckus.brouhaha.com> <823e82d6-4faf-453f-9330-a34c262c2f52@e25g2000prg.googlegroups.com> <13rmlqa9hc2344b@corp.supernews.com> <52dba0a7-6e8d-410a-b15b-276b90395fb5@i12g2000prf.googlegroups.com> Message-ID: <13rnb5moderbde8@corp.supernews.com> On 2008-02-19, castironpi at gmail.com wrote: > What is a a homile? It's a misspelling of homily. :) -- Grant Edwards grante Yow! It's hard being at an ARTIST!! visi.com From darcy at druid.net Tue Feb 26 12:12:22 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 26 Feb 2008 12:12:22 -0500 Subject: How about adding rational fraction to Python? In-Reply-To: References: <97f30679-483d-4751-9a6e-0858b36eb426@d4g2000prg.googlegroups.com> <649ac8a9-ae09-4e9b-85c2-f37043af21fd@28g2000hsw.googlegroups.com> <0d1955fc-762c-44e1-a5d8-372c71458455@p25g2000hsf.googlegroups.com> <36204e6f-0d82-449b-8ca5-c819ace9a55a@p73g2000hsd.googlegroups.com> <9503b14b-7bd5-42b4-b3f7-673d0ebd7feb@c33g2000hsd.googlegroups.com> <602ac27c-4aaa-49b2-bee2-1e0e0c705983@i7g2000prf.googlegroups.com> Message-ID: <20080226121222.5a60e19b.darcy@druid.net> On Tue, 26 Feb 2008 09:01:57 -0800 Jeff Schwab wrote: > Or Jo thinks // is a typo, and helpfully "fixes" it. Exactly. "Programmers" who use a language without learning it are apt to do anything. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From lizhongan at gmail.com Sun Feb 24 19:12:59 2008 From: lizhongan at gmail.com (zaley) Date: Sun, 24 Feb 2008 16:12:59 -0800 (PST) Subject: Is there a open souce IDE writen by C( C++) or partly writen by C( C++)? References: <42a838b9-2023-4cbf-bc53-e7ac5f4accbc@i7g2000prf.googlegroups.com> <47BE6D27.7000305@behnel.de> <47bee4d6$0$15901$edfadb0f@dtext01.news.tele.dk> Message-ID: <3c7c8149-2407-45a2-be67-d59b080f8ee4@s13g2000prd.googlegroups.com> On 2?25?, ??6?34?, Ricardo Ar?oz wrote: > zaley wrote: > > On Feb 24, 6:48 am, Ricardo Ar?oz wrote: > >> Lie wrote: > >>> On Feb 23, 4:02 pm, zaley wrote: > >>>> On Feb 22, 11:06 pm, "Jesper" wrote: > >>>>> Give PyScripter fromhttp://www.mmm-experts.com/atry > >>>>> It is for Windows, though it is written in Delphi and not in C/C++ > >>>>> /Jesper > >>>>> "zaley" skrev i en meddelelsenews:c1528422-5db2-4193-919b-b0a851d973f4 at b29g2000hsa.googlegroups.com... > >>>>> Of course, python scripts debugger > >>>>> On 2??22??, ????3??22??, zaley wrote: > >>>>>> My project need a simple scripts debugger . I hope I can find > >>>>>> something instructive > >>>>>> Stefan Behnel ?????? > >>>>>>> zaley wrote: > >>>>>>>> Is there a open souce IDE writen by C( C++) or partly writen by C( C+ > >>>>>>>> +)? > >>>>>>> Tons of them. What do you want to do with it? > >>>>>>> Stefan- Hide quoted text - > >>>>> - Show quoted text - > >>>> But PyScripter is not a open source project > >>> Am I correct to say that the reason why you wanted an open source C++ > >>> IDE is because you wanted the freedom to modify your own programming > >>> environment? > >> >From the "About" window in PyScripter : > > >> """ > >> A freeware, open source Python scripter integrated > >> development environment created with the ambition to bring to > >> the Python community the quality and functionality available in > >> commercial IDEs available for other languages. > >> """ > > >> So I think we could say PyScripter IS an open source project.- Hide quoted text - > > >> - Show quoted text - > > > Really, what I want to do is that scripts can be executed step by > > step . > > I know By "Py_Runstring" clauses in main function can executed by > > step . > > But I can't know how to step into a function and how to step in a > > function. > > So I hope I can find something helpful in open source IDE for python. > > Exactly so. PyScripter does it easy, besides you can have in different > tabs all the modules of your application. You just hit the run button > and your program runs, you hit the debug button and you start going step > by step. It's free, easy to install, just give it a try and if you don't > like it just trash it. I just want to know how to realize it in my program !! From paul at boddie.org.uk Sun Feb 3 18:31:49 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 3 Feb 2008 15:31:49 -0800 (PST) Subject: Is it explicitly specified? References: <60lqmqF1rkeiqU1@mid.individual.net> <60m2qnF1rgp7fU1@mid.uni-berlin.de> <9d3145c0-1128-4f7e-a9b5-2789f9231f34@1g2000hsl.googlegroups.com> Message-ID: On 3 Feb, 16:41, mario wrote: > > In one case, the collection attributes a specific meaning to > attr=None, but the actual default for attr is something else. However, > if an object explicitly wants to state that his attr=None (that is a > valid value, and has specific meaning) I would like to use that as > value, but if no value is supplied for attr by the object, then I > would like to use the default value from the collection. I don't know whether I can offer much better advice than others, but I have noticed that a lot of my own code has moved in the direction of not having specific default values in function/method signatures. So, instead of this... def f(x=123): ... ...I have this: def f(x=None): if x is None: x = 123 Of course, you can shorten this to "x = x or 123", but consider what might happen if x is given as 0. As for exposing the defaults, it's always possible to define them elsewhere, something which is very feasible with classes: class X: default = 123 def f(self, x=None): if x is None: x = self.default # or X.default The main reason for avoiding preset defaults has been to allow unspecified values to "cascade" through several levels of functions, if required, with the default being chosen at the most appropriate place. Now, your problem would involve explicitly specified values of None which would inadvertently cause the default to be used in the above cases. As others have said, a "sentinel" or special value would probably be a good replacement for None: class NotSetType: pass NotSet = NotSetType() # or just use object() def f(x=NotSet): if x is NotSet: x = 123 You could even explicitly pass NotSet to the function, too. Paul From castironpi at gmail.com Sun Feb 17 15:43:01 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 17 Feb 2008 12:43:01 -0800 (PST) Subject: call 'the following function' using decorators References: <4881cc78-85cc-4cf4-8e70-8089374d08f9@v17g2000hsa.googlegroups.com> <2050a2fa-0026-4923-9e5f-d3b4b53e4959@e25g2000prg.googlegroups.com> Message-ID: <6316f9f0-b21a-4edf-bcea-0c070d8f1867@d5g2000hsc.googlegroups.com> On Feb 15, 7:54?pm, castiro... at gmail.com wrote: > > > > > I assert it's easier to write: > > > > > > start_new_thread( this_func ) > > > > > def thrA(): > > > > > ? ? normal_suite() > > > > > > than > > > > > > def thrA(): > > > > > ? ? normal_suite() > > > > > start_new_thread( thrA ) > > > > > > If you don't, stop reading. > > Nothing beats if forkthread(): but what are the chances of getting it > in Python? AIR, as I recall, the SML equivalent is: var TM: thread_manager in def forkthread(): TM.add( True, False ) in if forkthread() thing_to_do() else other_thing_to() where programs can refer to a thread_manager along with a memory, which yes, is even in a functional language, well-defined. thread_manager altertantely beta-reduces one expression at a time in round-robin succession. thread_manager.add duplicates the current expression, and evaluates to True in one and False in the other. From steve at REMOVE-THIS-cybersource.com.au Thu Feb 14 10:47:16 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 14 Feb 2008 15:47:16 -0000 Subject: InstanceType tests in Python-3.0 References: Message-ID: <13r8ok4l36kr6af@corp.supernews.com> On Thu, 14 Feb 2008 15:26:08 +0000, Robin Becker wrote: > I'm in the process of porting some code. I have 2.x code that looks like > this > > t = type(e) > if t==InstanceType: > return f0(e) > elif t in (float,int): > return f1(e) > else: > return str(e) What happens if e is an instance of a subclass of int, or str? I'd write the above like this: if isinstance(e, type.InstanceType): # old-style classes don't exist in Python 3 return f0(e) elif isinstance(e, (float, int)): return f1(e) else: return str(e) Now all you have to do is work out what to do with new-style classes... > In python 3.0 everything has been unified and people say use attributes > to tell what should be done in such a branch. Well, you know what people say about people who listen to everything people say. What do you mean "everything" has been unified? What do you mean "use attributes to tell what should be done"? > However, this is the real world No, this is SPARTA!!! (Sorry, I couldn't resist. And I didn't even like the movie.) > and this code is fairly complex. Originally we had a distinction > between user defined class instances and those of the builtins like > float, int, str etc etc. Is there any way for me to tell if an object is > an instance of a used defined class which can then be tested further > perhaps? Why do you care if it is a user-defined class or not? What are you actually trying to accomplish? What's your aim in doing this testing? -- Steven From grante at visi.com Fri Feb 8 10:31:46 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 08 Feb 2008 15:31:46 -0000 Subject: OT: Star Wars and parsecs [was Re: Why not a Python compiler?] References: <28eead2f-a40c-414b-bd3d-a941f8a851a2@d70g2000hsb.googlegroups.com> <7da40f42-f64f-4939-a0dc-d24d1ff85f2d@v4g2000hsf.googlegroups.com> <13qjktdbe76da00@corp.supernews.com> <13qmp56btnr55a4@corp.supernews.com> <13qmtqebm4t6979@corp.supernews.com> <13qo0rkr7osv792@corp.supernews.com> Message-ID: <13qotf2mgpvkoac@corp.supernews.com> On 2008-02-08, Dennis Lee Bieber wrote: > A Parsec is a fixed value (which, admittedly, presumes the culture > developed a 360degree circle broken into degrees => minutes => > seconds... or, at least, some units compatible with the concept of an > "arc second", like 400 grads of, say, 100 "minutes", each of 100 > "seconds") It also presumes a standard diamter of that circle. -- Grant Edwards grante Yow! Are you the at self-frying president? visi.com From see.signature at no.spam Mon Feb 4 06:20:29 2008 From: see.signature at no.spam (Eric Brunel) Date: Mon, 04 Feb 2008 12:20:29 +0100 Subject: What should I use under *nix instead of freeze? References: <7498f946-9ea6-48fe-a509-c80cf425af11@j78g2000hsd.googlegroups.com> Message-ID: On Sat, 02 Feb 2008 00:08:21 +0100, Mike Kent wrote: > In a comment Guido made on a recent bug report for the 'freeze' > utility, he stated: > > "I think nobody really cares about freeze any more -- it isn't > maintained." > > That being the case, what is the preferred/best replacement for freeze > on a *nix platform? I'm looking for something that, like freeze, > turns my application into a single-file executable, of the smallest > size possible, that can be executed on a machine with no Python > installation or development system. Never used it, but it seems cx_Freeze (http://python.net/crew/atuining/cx_Freeze/) does just that... Don't know if it's maintained anymore, but versions are available for the latest Python version (2.5). HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From jorgen.maillist at gmail.com Thu Feb 7 11:16:05 2008 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Thu, 7 Feb 2008 17:16:05 +0100 Subject: Small problem executing python script as shortcut Message-ID: <11e49df10802070816k65544been5ad199bbb75353bb@mail.gmail.com> Hi all, This is slightly OT but it drives me nuts. Whenever I create a shortcut in the start menu (in Windows) of a python script, it will only execute it when the path where the script resides in contains no spaces. For example; d:\src\app\app.py If I drag that to the Start Menu it can be executed fine. Whenever I distribute my app and the path will become: "c:\program files\app\app.py" Windows will make spaces itself inside the shortcut so I guess it realizes that it needs to execute the full string but probably somewhere when resolving the app to execute the script with, the double quotes get lost and the python interpreter (I use ActiveState as my Python bundle) will only see "c:\program" as the first part and doesn't pick up the latter. I know I can write a batch script that runs the python script, but since it is a wxPython app, I want to launch a *.pyw to suppress the dos box. However as it seems now there is no way to create a shortcut under windows to launch a python script when the directory contains spaces in the name. Does anyone know a solution? I would like to distribute my app both with py2exe (no problems there) but also as source only version so people can adjust the code if they wish. Regards, - Jorgen From aantny at gmail.com Wed Feb 6 06:22:09 2008 From: aantny at gmail.com (Natan Yellin) Date: Wed, 6 Feb 2008 03:22:09 -0800 (PST) Subject: Retreiving objects from other processes Message-ID: <19b182bc-b40d-478c-96b7-6894ab3072a9@v67g2000hse.googlegroups.com> Hello, Sorry if this is a stupid question... I have some experience with C but very little with Python. I'd like to have one python program retrieve a reference or copy of an object from another python process on the same computer. I know I can use RPyC, but that seems like overkill. Is there simpler way of doing it? Thanks in advance, Natan From Lie.1296 at gmail.com Fri Feb 29 20:29:32 2008 From: Lie.1296 at gmail.com (Lie) Date: Fri, 29 Feb 2008 17:29:32 -0800 (PST) Subject: How about adding rational fraction to Python? References: <13scs8k1kh9nk81@corp.supernews.com> <13see4t3s23pn59@corp.supernews.com> <9cd8f360-da6b-4a9d-a21c-c93adfd5cc20@i29g2000prf.googlegroups.com> Message-ID: <938df38f-40b2-4d06-beee-4b0bf2b195fa@e6g2000prf.googlegroups.com> On Feb 28, 10:00 am, Paul Rubin wrote: > More examples: > > x = 1 > y = len(s) + x > > => ok, decides that x is an int > > x = 1 > y = x + 3.0 > > => ok, decides that x is a float > > x = 1 > y = x + 3.0 > z = len(s) + x > > => forbidden, x cannot be an int and float at the same time. > > > I am so glad you're not the designer of Python. > > This is how Haskell works and I don't notice much complaints about it. Ok, that means the line "y = x + 3.0" have a side effect of "x = float(x)"? I think I would say that is an implicit behavior. On Feb 28, 11:22 pm, "D'Arcy J.M. Cain" wrote: > > You people can't tell the difference between "obvious" and "learned > > conventions that came about because in limitations in the hardware at > > the time". Nobody would have come up with a silly rule like "x op y > > must always have the same type as x and y" if computer hardware had > > been up to the task when these languages were created. > > What makes you say they weren't? Calculating machines that handled > floating point are older than Python by far. > But much younger than the first programming language (if it could be called as a language) that set the convention of int op int should result in int 'cause our hardware can't handle floats. On Feb 29, 6:15 am, Paul Rubin wrote: > Can you name an example of a calculating machine that both: > 2) says 1/2 = 0.5 ? Any pocket calculator to scientific calculator. Except perhaps my calculator which is fraction scientific calculator where it stores 1/2 as rational and have another division operator for 1/2 == 0.5 From cwitts at gmail.com Tue Feb 5 14:27:36 2008 From: cwitts at gmail.com (Chris) Date: Tue, 5 Feb 2008 11:27:36 -0800 (PST) Subject: Broke my IDLE! References: <1e6ec8dc-3fa4-4e75-86c1-26852ea30a65@n20g2000hsh.googlegroups.com> Message-ID: <48a7d2e5-88f3-4760-9eac-3ae728ad3e13@v4g2000hsf.googlegroups.com> On Feb 5, 7:05 pm, "Adam W." wrote: > Tried running IDEL from the command prompt to get this: > > Traceback (most recent call last): > File "c:\Python25\Lib\idlelib\idle.pyw", line 21, in > idlelib.PyShell.main() > File "c:\Python25\lib\idlelib\PyShell.py", line 1404, in main > shell = flist.open_shell() > File "c:\Python25\lib\idlelib\PyShell.py", line 275, in open_shell > self.pyshell = PyShell(self) > File "c:\Python25\lib\idlelib\PyShell.py", line 813, in __init__ > OutputWindow.__init__(self, flist, None, None) > File "c:\Python25\lib\idlelib\OutputWindow.py", line 16, in __init__ > EditorWindow.__init__(self, *args) > File "c:\Python25\lib\idlelib\EditorWindow.py", line 125, in > __init__ > self.apply_bindings() > File "c:\Python25\lib\idlelib\EditorWindow.py", line 900, in > apply_bindings > text.event_add(event, *keylist) > File "c:\Python25\lib\idlelib\MultiCall.py", line 345, in event_add > widget.event_add(self, virtual, seq) > File "c:\Python25\lib\lib-tk\Tkinter.py", line 1357, in event_add > self.tk.call(args) > _tkinter.TclError: extra characters after detail in binding > > What do I need to edit and change? Python25\Lib\idlelib\config-keys.def From Graham.Dumpleton at gmail.com Sun Feb 3 18:40:03 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Sun, 3 Feb 2008 15:40:03 -0800 (PST) Subject: apache/mod_wsgi daemon mode References: Message-ID: <0676dd01-1284-43e8-bbc1-223500f88c4b@v29g2000hsf.googlegroups.com> On Feb 4, 10:33 am, Scott SA wrote: > On 2/3/08, Brian Smith (br... at briansmith.org) wrote: > >Scott SA wrote: > >> I am trying to configure mod_wsgi to run in daemon mode with > >> Apache. I can easily get it to run 'normally' under Apache > >> but I obtain permission errors _or_ process-failures in > >> daemon mode. Specifically: > > >> ... (13)Permission denied: mod_wsgi (pid=26962): Unable > >> to connect > >> to WSGI daemon process '' on > >> '/etc/httpd/logs/wsgi.26957.0.1.sock' after multiple attempts. > > ... > > I had previoiusly done what I _thought_ was a good job of searching the wsgi mailing list (really!). A reworking of my google search parameters finally yeildd a helpful thread: > > > > The problem was WSGI trying to create its .sock file in /var/log/httpd but failing and therefore not running at all. The user I had specified did not have enough permissions to do so (part of the point _of_ running in daemon mode, LOL). Oddly, I had attempted to grant the permissions for the user but see now there was an error in how I did that... oops. > > By adding the following to my config: > > WSGISocketPrefix /tmp/wsgi Also documented in: http://code.google.com/p/modwsgi/wiki/ConfigurationIssues Since you have given a real live example error message from logs for when it goes wrong, I'll be able to include this in the documentation. That may make it easier for others to find that page when they do a Google search. At the moment the page only mentioned that you would get a '503 Service Temporarily Unavailable' response in browser. Graham > We now have successss! > > So my config now looks like: > > WSGISocketPrefix /tmp/wsgi > > > ServerName host.domain.com > > WSGIDaemonProcess user= group= threads=10 \ > maximum-requests=500 > > WSGIScriptAlias /something /path/to/
  
MMEETTEEOO
Warning: ActiveScripting must be authorized (inside IE) Another way is to drive Interne-Explorer from Python. it's possible to call (& return) Javascript functions & code, from Python, with parameter. It's more complicated, but with more possibilities. For PLUIE, it's the way which I chose. @-salutations Michel Claveau From davidj411 at gmail.com Thu Feb 28 17:56:10 2008 From: davidj411 at gmail.com (davidj411) Date: Thu, 28 Feb 2008 14:56:10 -0800 (PST) Subject: convert string number to real number - ValueError: invalid literal for int() with base 10: '"2"' Message-ID: <3ca86e1d-a32f-48f2-bc9a-6cb792c0c631@z17g2000hsg.googlegroups.com> i am parsing a cell phone bill to get a list of all numbers and the total talktime spend on each number. i already have a unique list of the phone numbers. now i must go through the list of numbers and add up the totals for each number. on the bill, each line has a few fields,one field containing the phone number, another field containing the number of minutes on that call. the bill is comma delimited. here is the function i wrote to get one number at a time's total talktime. def getsinglenumbertalktime(number,talktime): for line in file[0:-2]: if number in line: li=line.split(',') if len(li)==6 and li[5]!="Minutes" : print "talktime type: " + str(type (talktime)) #li[5]=fpformat.fix(li[5],0) print li[5] + "li[5] type: " + str(type(li[5])) newvar = int(li[5]) print (type(newvar)) print li[5] talktime = talktime + li[5] return talktime here is the output with error that i get back. talktime type: "2"li[5] type: Traceback (most recent call last): File "", line 1, in File "c:\path\inprog\all_t_mob_nums.py", line 74, in getsinglenumbertalktime('"800-218-2644"',talktime) File "c:\path\inprog\all_t_mob_nums.py", line 66, in getsinglenumbertalktime newvar = int(li[5]) ValueError: invalid literal for int() with base 10: '"2"' here is the question: How can i convert a string number like "2" to a true number that can be added. I have tried using pfformat, float(), and int() - all with no good results. this seems like is should be simple, but it just plain isn't. I actually found a good solution. basically, take each entry and add it to a list. then iterate through the list , converting each item to int(). then add them to sum them all up. FINAL SOLUTION: def getsinglenumbertalktime(number,talktime): num_of_calls=0 num_mins=[] for line in file[0:-2]: #print "LINE: " + line #print number in line if number in line: num_of_calls += 1 #print number,num_of_calls li=line.strip("\n") #print "stripped:" + line li=li.split(',') #print "split: " + str(li) #print "len of li: " + str(len(li)) + str(num_of_calls) if len(li)==7 and li[5]!="Minutes" : #print "talktime type: " + str(type (talktime)) #print li[4] + "li[4] type: " + str(type(li[5])) #newvar = fpformat.fix(li[4],0) #print (type(newvar)) #print "len 7: " + str(type(li[6])) num_mins.append(li[6]) #talktime = talktime + int(a) if len(li)==6 and li[5]!="Minutes" : #print "talktime type: " + str(type (talktime)) #print li[5] + "li[5] type: " + str(type(li[5])) #newvar = fpformat.fix(li[4],0) #print (type(newvar)) #print "len 6: " + str(type(li[5])) num_mins.append(li[5]) #talktime = talktime + int(a) #return talktime , num_of_calls x=0 #print "this" + str(number) + str(num_mins) for a in num_mins: b=int(a) x=x+b print str(number), str(x), str(type(x)) output should look like this (parts of script are not included) 555-555-5555 replaced the innocent :P): 555-555-5555 19 555-555-5555 6 555-555-5555 3 555-555-5555 3 555-555-5555 2 555-555-5555 52 From python.list at tim.thechases.com Tue Feb 26 11:01:13 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 26 Feb 2008 10:01:13 -0600 Subject: Break lines? In-Reply-To: References: Message-ID: <47C437C9.4020004@tim.thechases.com> > I have made this string: > > TITLE = 'Efficiency of set operations: sort model, > (cphstl::set::insert(p,e)^n cphstl::set::insert(e)), integer' > > But I am not allowed to break the line like that: > > IndentationError: unexpected indent > > How do I break a line? Depends on what you want. You can embed running strings with newlines using triple-quotes (either single- or double-quotes): TITLE = """Efficiency... (cphstl:...""" Or you can use string concatenation using line-continuations: TITLE = "Efficiency..." \ "(cphstl:..." or using parens TITLE = ("Efficiency..." "(cphstl:...") I like the clean'ness of the first version, but sometimes get irked by it including my leading whitespace (there are some workarounds, but all involve more than trivial effort). I tend to use the 2nd in the case you describe, but usually using the 3rd version in all other cases where it's as a parameter to a function call or some other bracketed/braced construct. -tkc From castironpi at gmail.com Fri Feb 29 12:26:31 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 29 Feb 2008 09:26:31 -0800 (PST) Subject: Indentation and optional delimiters References: <555b548f-1296-4374-b6ce-65691d1dbb7f@s8g2000prg.googlegroups.com><13s92u3sibaus4f@corp.supernews.com><3f55d3b1-c32c-42bc-bd4b-52e2725049b0@v3g2000hsc.googlegroups.com><13scm5m9jmdns02@corp.supernews.com> <318b03dc-4cc5-49de-aeb9-e1b6e590007f@u10g2000prn.googlegroups.com> Message-ID: <6344c250-4070-4bb7-980a-9661fc789c59@d62g2000hsf.googlegroups.com> On Feb 29, 8:59?am, Steve Holden wrote: > Steve Holden wrote: > > castiro... at gmail.com wrote: > > [...] > > ?> If you want a computer language to model human thought, then is there > >> even such thing as subclassing? > > > Kindly try to limit your ramblings to answerable questions. Without keen > > insight into the function of the mind that is currently available to the > > psychological and psychiatric professions, such philosophical > > speculation is unlikely to do anyone any good, least of all you. > > ^available^unavailable^ > -- > Steve Holden ? ? ? ?+1 571 484 6266 ? +1 800 494 3119 > Holden Web LLC ? ? ? ? ? ? ?http://www.holdenweb.com/ In the neuroscience book I read (_Neuroscience_), my favorite section was entitled, "Mechanisms of Long-Term Synaptic Plasticity in the Mammalian Nervous System." Maybe reptiles do, I guess. ... and Python -is- a reptile... From brian at briansmith.org Sat Feb 16 16:47:22 2008 From: brian at briansmith.org (Brian Smith) Date: Sat, 16 Feb 2008 13:47:22 -0800 Subject: Is there a way to "link" a python program from several files? In-Reply-To: <61or3kF1ssn8aU1@mid.uni-berlin.de> References: <61or3kF1ssn8aU1@mid.uni-berlin.de> Message-ID: <002101c870e5$837da390$6501a8c0@T60> Diez B. Roggisch wrote: > Edward A. Falk schrieb: > > IOW, is there a "linker" for python? I've written a > > program comprised of about five .py files. I'd like to > > find a way to combine them into a single executable. > > Obviously, I could hand-edit them into a single > > .py file, but I'm looking for a way to keep them as > > seperate files for development but distribute the > > result as a single file. > Depending on the OS, there are several options. Ranging from > distributing an .egg (setuptools) over py2exe for windows to > py2app on OSX - and some more, e.g. cx_freeze. I would be interested in a program that can combine multiple modules into a single module, which removes all the inter-package imports and fixes other inter-module references, like Haskell All-in-One does for Haskell: http://www.cs.utah.edu/~hal/HAllInOne/index.html - Brian From lasses_weil at klapptsowieso.net Sun Feb 3 14:36:18 2008 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Sun, 03 Feb 2008 20:36:18 +0100 Subject: Project naming suggestions? In-Reply-To: References: Message-ID: <47a617d1$0$5956$9b4e6d93@newsspool3.arcor-online.net> miller.paul.w at gmail.com wrote: > I'm considering writing a little interpreter for a python-like > language and I'm looking for name suggestions. :-) > How about "Whython"? /W From ebgssth at gmail.com Sun Feb 24 01:03:10 2008 From: ebgssth at gmail.com (js) Date: Sun, 24 Feb 2008 15:03:10 +0900 Subject: Official IRC channel for Python? In-Reply-To: References: <7xskzj7yw9.fsf@ruckus.brouhaha.com> Message-ID: No. Actually, i'm very new to IRC. On Sun, Feb 24, 2008 at 2:55 PM, Steve Holden wrote: > js wrote: > > Really? maybe I'm been blocked from it... > > thanks. > > > Currently 479 users. Have you been blocked from many channels? > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC http://www.holdenweb.com/ > > -- > > > http://mail.python.org/mailman/listinfo/python-list > From wolf_tracks at invalid.com Sun Feb 17 23:30:46 2008 From: wolf_tracks at invalid.com (W. Watson) Date: Sun, 17 Feb 2008 20:30:46 -0800 Subject: Pmw Use and Grayson's Book In-Reply-To: <74f10874-8568-4815-8eb0-a92a3301db14@34g2000hsz.googlegroups.com> References: <74f10874-8568-4815-8eb0-a92a3301db14@34g2000hsz.googlegroups.com> Message-ID: I wonder why he uses it? If I want to run his examples, where do I put the lib he includes? Same folder as the example? Mike Driscoll wrote: > On Feb 17, 9:33 pm, "W. Watson" wrote: >> I don't have Grayson's Tkinter book, but I see he uses something called Pmw. >> Why is it needed with Tkinter? >> -- >> Wayne Watson (Nevada City, CA) >> >> Web Page: > > It's not needed. It's just an extra set of widgets that are not > included in the standard set. As I recall, PMW = Python Mega-Widgets. > Check out their site: > > http://pmw.sourceforge.net/ > > You'll probably also come across Tix, another subset of widgets, which > I think is now included with Python be default from 2.4 on up. It > should be noted that PMW is not included with the standard Python > distro though. > > Mike -- Wayne Watson (Nevada City, CA) Web Page: From planders at gmail.com Tue Feb 26 11:59:37 2008 From: planders at gmail.com (Preston Landers) Date: Tue, 26 Feb 2008 08:59:37 -0800 (PST) Subject: is there enough information? References: <56783fab-c5c5-4e42-a0fb-519f75beb65a@72g2000hsu.googlegroups.com> <0f240e82-04de-497f-a9aa-07458fc97235@b1g2000hsg.googlegroups.com> <03d54be8-b1a8-455b-9e1f-c75626aedc3e@72g2000hsu.googlegroups.com> Message-ID: On Feb 26, 1:45 am, castiro... at gmail.com wrote: > Two options occurred to me, which the first showed up in the earlier > extremely skeletal and cryptic post: Perhaps you would be more likely to get the kind of help you seem to want if you refrained from posting "cryptic and skeletal" messages. The fact that many other people have pointed this out to you as of late would tend to suggest you are trolling, i.e. intentionally trying to foster miscommunication and threads that do nothing to advance anyones understanding. And regarding your other recent post about trying to find a "solution" to the "problem" of immutable types... Due to the above reasons you are unlikely to influence the design of the core language with half-baked stream of consciousness ramblings. These belong in your LiveJournal, not in c.l.python. If you have a problem you need help with, please read this entire document about 3 times before posting anything else: http://catb.org/~esr/faqs/smart-questions.html Specifically this: http://catb.org/~esr/faqs/smart-questions.html#beprecise and this: http://catb.org/~esr/faqs/smart-questions.html#goal From cokofreedom at gmail.com Wed Feb 20 06:12:39 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 20 Feb 2008 03:12:39 -0800 (PST) Subject: Double underscores -- ugly? References: <8cee096e-7f27-4162-ae09-e0fdbbc91db6@s8g2000prg.googlegroups.com> <47bb03d6$0$4281$9b4e6d93@newsspool3.arcor-online.net> <2671c516-5476-4d2b-ab33-fdf583b56316@72g2000hsu.googlegroups.com> <87zltwi8od.fsf@benfinney.id.au> <8971b484-861b-4a1b-b933-f50af7333d05@z17g2000hsg.googlegroups.com> <47bc0877$0$6144$426a74cc@news.free.fr> Message-ID: <74cc4205-ccb5-445d-9890-d5ce3b5dddfa@f47g2000hsd.googlegroups.com> So people's problem with __word__ is that it is not very readable? How so, it stands out on page, it clearly is different from other objects and doesn't abuse other symbols that generally have a meaning based on their use. I haven't seen a single alternative that really stands out as much as __word__ does. From mani.sabri at gmail.com Sun Feb 10 03:20:40 2008 From: mani.sabri at gmail.com (mani) Date: Sun, 10 Feb 2008 00:20:40 -0800 (PST) Subject: Why not a Python compiler? References: <28eead2f-a40c-414b-bd3d-a941f8a851a2@d70g2000hsb.googlegroups.com> <7da40f42-f64f-4939-a0dc-d24d1ff85f2d@v4g2000hsf.googlegroups.com> Message-ID: <05858001-97ed-4452-87c1-b1fa4cb10ea8@c23g2000hsa.googlegroups.com> On Feb 6, 2:43 am, "Luis M. Gonz?lez" wrote: > On 5 feb, 05:19, Santiago Romero wrote: > > > > > ( Surely if this question has been asked for a zillion of times... ) > > ( and sorry for my english! ) > > > I'm impressed with python. I'm very happy with the language and I > > find Python+Pygame a very powerful and productive way of writing 2D > > games. I'm not, at this moment, worried about execution speed of the > > small game I'm working on (it runs at full 60 fps even in an old AMD- > > K6 450 Laptop computer), but I continue asking me the same question: > > > Why not a Python COMPILER? > > > It would be very nice to be able to output Linux, MAC or Windows > > binaries of compiled (not bytecompiled) code. It would run faster, it > > will be smaller in size (I think) and it will be easy to distribute to > > people not having python installed. Yes, I know about py2exe, but I'm > > not sure if that's the right aproach. > > > So, what's wrong with compiling python? > > > Maybe is not possible due to nature of the language? Is just a > > decision? > > > What do you think about this? > > There are some projects aimed to speed up Python by a large margin. > Right now you can use psyco, which is considered to be feature > complete, and whose future relies on the Pypy project. > > Pypy is a very ambitious project and it aims, amongst many other > goals, to provide a fast just-in-time python implementation. > They even say that the "secret goal is being faster than c, which is > nonsense, isn?t it?" (I still didn?t get the joke though...). > > And finally, you have ShedSkin, a project developed by one lonely and > heroic coder (Mark Dufour). > Shedskin aims at being a static python compiler, which can translate a > subset of python to stand alone executables. > It also can compile extension modules for cpython. > It works by translating python to c++ and then to machine code. > The python code must be done in a static way (getting rid of dynamic > features like, for example, not asigning different types to the same > variable). > > Luis and Take a look at this page if you look for a plan to develop a fast python program, you wont regret it. http://ondrej.certik.cz/development/ Mani From nytrokiss at gmail.com Wed Feb 13 09:58:03 2008 From: nytrokiss at gmail.com (James Matthews) Date: Wed, 13 Feb 2008 15:58:03 +0100 Subject: win32com.client question In-Reply-To: References: Message-ID: <8a6b8e350802130658p7bb71365o161aa57c14735314@mail.gmail.com> What do you mean possible? On Feb 13, 2008 3:05 PM, Juan_Pablo wrote: > import win32com.client > is posible in linux ? > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://search.goldwatches.com/?Search=Movado+Watches http://www.jewelerslounge.com http://www.goldwatches.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyosohma at gmail.com Thu Feb 21 20:20:46 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 21 Feb 2008 17:20:46 -0800 (PST) Subject: OT: Ideas for a first course using Python References: Message-ID: On Feb 21, 4:48 pm, ishwar.rat... at gmail.com wrote: > Sorry to butt in but I am shopping for some ideas. > > I am interested in putting together a programming course for non- > programmers (outside the computer science domain) based on Pyhton. I > envision the course > similar to ones that used old-Basic interpreter. > > Any one out there has such a course (already designed) or has some > experience > of such a course? > > What could be a list of topics to be addressed in such a course > (domain), other > than the language syntax? > > -ishwar This guy's been doing it for a while now as a college course: http://mcsp.wartburg.edu/zelle/python/python-first.html Mike From jzgoda at o2.usun.pl Mon Feb 11 14:53:39 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Mon, 11 Feb 2008 20:53:39 +0100 Subject: Help with jabber client in wx In-Reply-To: References: Message-ID: Astan Chee pisze: > A quick note, the project started as a google talk client, but it seems > that xmpppy is flexible enough to support various other/similar XMPP > servers, but I mainly use with/in google talk > It is open source and I've included the windows executable as an > optional download. > The current problem Im having is that whenever the jabber client > disconnects or whenever a network error occurs (ISP goes down,etc), the > client does not reconnect. I've added some code to help this, but it > still doesnt reconnect properly; or rather, it doesnt detect the > disconnection properly. What am I doing wrong in the xmpppy > classes/methods? If you want to use xmppy, I'd suggest looking at Gajim team modifications to original source (http://gajim.org/). These guys did a whole lot of work making xmppy more standards compliant and fixing bugs. -- Jarek Zgoda http://zgodowie.org/ "We read Knuth so you don't have to" - Tim Peters From xng at xs4all.nl Wed Feb 13 16:15:22 2008 From: xng at xs4all.nl (Martin P. Hellwig) Date: Wed, 13 Feb 2008 22:15:22 +0100 Subject: Email Directly from python In-Reply-To: References: <47b35ab7$0$8718$e4fe514c@dreader24.news.xs4all.nl> Message-ID: <47b35e52$0$8745$e4fe514c@dreader24.news.xs4all.nl> brad wrote: > Martin P. Hellwig wrote: > >> The tricky part is how to resolve the mail server for a mail address. >> Usually you have to query the mx record of that domain. I solved that >> by looking if I can find the nslookup binary. > > The from and to are static constants... they don't change. Mail just > seems so tricky these days what with all the blacklists, greylists, > whitelists, etc. It's almost as if email is broken. Location of the > sending pc matters too. Just wondering if there is a super simple one > liner in Python (that's portable) that can do this. > Well the problem is that you can't control whether the to address won't be handled with a different mail server in the future. Whether the receiving party marks your mail as spam or not is actually their problem. If you act according to the RFC's it should be delivered. Of course it helps if you don't make the content be spam ;-) -- mph From roger.dahlstrom at gmail.com Mon Feb 4 14:25:00 2008 From: roger.dahlstrom at gmail.com (rdahlstrom) Date: Mon, 4 Feb 2008 11:25:00 -0800 (PST) Subject: Windows - remote system window text References: <3b29a22b-55cd-4430-9a47-cba4941e9b8c@h11g2000prf.googlegroups.com> <9d71dbbb-240a-44c5-9e3f-ef223133152e@z17g2000hsg.googlegroups.com> Message-ID: <11db701c-d1f2-4970-8f83-df214bdca7c5@b2g2000hsg.googlegroups.com> On Feb 4, 2:17 pm, "m... at infoserv.dk" wrote: > Well, i guess you will need a process on each machine you need to > monitor, and then you do have a client server setup. > > This can be easily accomplished with fx Pyro (http:// > pyro.sourceforge.net/) for communication, and the Win32 Python library > (https://sourceforge.net/projects/pywin32/) for creating a service. Crap, that's what I didn't want to do. I am slowly coming to the realization that I'm going to have to, but I really didn't want to do that. That brings up a whole host of other things that I would then have to do - remote installation, etc. I guess I could do it, but I'd really rather not. From bellman at lysator.liu.se Tue Feb 5 13:14:28 2008 From: bellman at lysator.liu.se (Thomas Bellman) Date: Tue, 5 Feb 2008 18:14:28 +0000 (UTC) Subject: polling for output from a subprocess module References: <48dec8a9-c2da-492c-a639-097fe25fe73c@s8g2000prg.googlegroups.com> Message-ID: Christian Heimes writes: > Thomas Bellman wrote: >> The readlines() method will read until it reaches end of file (or >> an error occurs), not just what is available at the moment. You >> can see that for your self by running: > Bad idea ;) Why is it a bad idea to see how the readlines() method behaves? > readlines() on a subprocess Popen instance will block when you PIPE more > than one stream and the buffer of the other stream is full. > You can find some insight at http://bugs.python.org/issue1606. I > discussed the matter with Guido a while ago. Umm... Yes, you are correct that the code in the original post also has a deadlock problem. I missed that. But saying that it is the readline() method that is blocking is a bit misleading, IMHO. Both processes will be blocking, in a deadly embrace. It's a problem that has been known since the concept of inter- process communication was invented, and isn't specific to the readlines() method in Python. But the OP *also* has the problem that I described in my reply. Even if he only PIPE:d one of the output streams from his subprocess, he would only receive its output when the subprocess finished (if it ever does), not as it is produced. (To those that don't understand why the OP's code risks a deadly embrace: if a process (A) writes significant amounts of data to both its standard output and standard error, but the process that holds the other end of those streams (process B) only reads data from one of those streams, process A will after a while fill the operating system's buffers for the other stream. When that happens, the OS will block process A from running until process B reads data from that stream too, freeing up buffer space. If process B never does that, then process A will never run again. The OP must therefore do a select() on both the standard output and standard error of his subprocess, and use os.read() to retrieve the output from both streams to free up buffer space in the pipes.) -- Thomas Bellman, Lysator Computer Club, Link?ping University, Sweden "We don't understand the software, and ! bellman @ lysator.liu.se sometimes we don't understand the hardware, ! but we can *see* the blinking lights!" ! Make Love -- Nicht Wahr! From cyberco at gmail.com Fri Feb 22 18:31:10 2008 From: cyberco at gmail.com (Berco Beute) Date: Fri, 22 Feb 2008 15:31:10 -0800 (PST) Subject: Web Development Project References: Message-ID: <4ce72423-4c0f-4cce-926b-efa76d735497@i7g2000prf.googlegroups.com> linux lighttpd fastcgi django sqlite3 ...rocking combo :) From rconradharris at gmail.com Thu Feb 14 13:42:38 2008 From: rconradharris at gmail.com (Rick Harris) Date: Thu, 14 Feb 2008 10:42:38 -0800 (PST) Subject: Copying weakrefs References: <7eac1891-66b2-4716-86f1-f85292b1c822@e25g2000prg.googlegroups.com> Message-ID: On Feb 14, 12:31 pm, Rick Harris wrote: > I am working with an object, Context, that maintains an identity map > by using the weakref.WeakValueDictionary. I would like to clone this > Context object (and objects that may have a Context object) using > copy.deepcopy(). When I try to do this, the deep copy operation > recurses down to the WeakValueDictionary, down to the KeyedRef > subclass of ref, and then fails. It seems that copy.copy() and > copy.deepcopy() operations on weakrefs just won't work. > > The failure can be replicated with this (much simpler) scenario: > > >>> import weakref, copy > >>> class Test(object): pass > >>> t = Test() > >>> wr = weakref.ref(t) > >>> wr_new = copy.copy(wr) # Fails, not enough args to __new__ > > Anybody out there have some insight into this? > > Thanks > Rick Update: I was able to monkey-patch the copy module's dispatch tables to (seemingly) fix this. The code is: >>> copy._copy_dispatch[weakref.ref] = copy._copy_immutable >>> copy._deepcopy_dispatch[weakref.KeyedRef] = copy._deepcopy_atomic Could somebody more familiar with Python internals look into whether this patch is a) correct and b) whether this should be added to copy module? Thanks, Rick From nick at stinemates.org Mon Feb 18 22:19:44 2008 From: nick at stinemates.org (Nick Stinemates) Date: Mon, 18 Feb 2008 19:19:44 -0800 Subject: name of client module In-Reply-To: References: <2KCdnWJQeaBuuCfanZ2dnUVZ_sednZ2d@comcast.com> Message-ID: <47BA4AD0.2030407@stinemates.org> Jeff Schwab wrote: > Nick Stinemates wrote: > >>> I'm not saying I don't want to do that. I'm saying that, in addition to >>> what you've written, I want foo to know it's being imported, and by whom. >>> > > Please don't snip so much. > > >> You're still not explaining a real example of what this could be used for. >> > > Why would you say something like that? I told you *exactly* what I > wanted to use it for. See Berwyn's post on the recent thread "Double > underscores -- ugly?" He suggests that a suitable replacement for "if > __name__ == '__main__'" might be "if sys.main()". I was looking for a > way to implement that kind of function. Just like I told you when you > asked me. You snipped it, along with most of the post. > > >> Oh well, here's an example of an implementation of what you want to do. >> > > Thanks. > Ah, I snipped because I was only replying to that specific part and thought there was an archive of the rest. If that is unconventional I'll stop. I suppose I did get a bit carried away. It seems people always want to know 'who is calling my object' but I think writing a design around that is: a) Really hard to follow, much like GoTo statements b) Poorly thought out and, probably much more importantly c) Grouping code together like that really limits what you can do with it.. I'm sorry if I offended. -- ================== Nick Stinemates (nick at stinemates.org) http://nick.stinemates.org AIM: Nick Stinemates MSN: nickstinemates at hotmail.com Yahoo: nickstinemates at yahoo.com ================== From john106henry at hotmail.com Thu Feb 21 16:53:53 2008 From: john106henry at hotmail.com (John Henry) Date: Thu, 21 Feb 2008 13:53:53 -0800 (PST) Subject: Return value of an assignment statement? References: <6d945394-739e-4c47-ad71-faaab8f9d566@34g2000hsz.googlegroups.com> <835a4fc1-f62a-4141-bca4-4e4f52519466@s37g2000prg.googlegroups.com> Message-ID: On Feb 21, 1:48 pm, John Henry wrote: > On Feb 21, 1:43 pm, mrstephengross wrote: > > > > > Hi all. In C, an assignment statement returns the value assigned. For > > instance: > > > int x > > int y = (x = 3) > > > In the above example, (x=3) returns 3, which is assigned to y. > > > In python, as far as I can tell, assignment statements don't return > > anything: > > > y = (x = 3) > > > The above example generates a SyntaxError. > > > Is this correct? I just want to make sure I've understood the > > semantics. > > > Thanks, > > --Steve > > That's true, and I am happy that they decided to make that a syntax > error. BTW: The less obvious issues when coming from the C world are Python syntax like these: y = x = 3 a = 4 y = x = a print x,y a = 5 print x,y From bearophileHUGS at lycos.com Thu Feb 14 06:26:24 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 14 Feb 2008 03:26:24 -0800 (PST) Subject: Regular Expression for Prime Numbers (or How I came to fail at them, and love the bomb) References: <85ca4615-c51f-4aab-b400-f3f80056faec@l32g2000hse.googlegroups.com> <81744abc-7542-4196-bbbf-9a0248805311@d21g2000prf.googlegroups.com> Message-ID: <454b9118-1639-4d9c-92f8-24f4f897755b@e10g2000prf.googlegroups.com> cokofree: > Sadly that is pretty slow though... It's quadratic, and it's not even short, you can do (quadratic still): print [x for x in range(2, 100) if all(x%i for i in range(2, x))] In D you can write similar code. Bye, bearophile From dhwild at talktalk.net Wed Feb 13 14:16:29 2008 From: dhwild at talktalk.net (David H Wild) Date: Wed, 13 Feb 2008 19:16:29 +0000 (GMT) Subject: OT: Speed of light References: <6f-dnfwZwvz6Ui3anZ2dnUVZ_oOnnZ2d@speakeasy.net> <13r2p6aivk1no9a@corp.supernews.com> <880dece00802121311n77f73515ve7db8a931825d958@mail.gmail.com> <87abm4g1tw.fsf@mulj.homelinux.net> <5LednYnShMTspS7anZ2dnUVZ_ternZ2d@comcast.com> Message-ID: <47b34916$0$1342$834e42db@reader.greatnowhere.com> In article <5LednYnShMTspS7anZ2dnUVZ_ternZ2d at comcast.com>, Jeff Schwab wrote: > We (Americans) all measure our weight in pounds. People talk about how > much less they would weigh on the moon, in pounds, or even near the > equator (where the Earth's radius is slightly higher). Their weight on the moon would be exactly the same as on earth if they used a balance with weights on the other side of the fulcrum. -- David Wild using RISC OS on broadband www.davidhwild.me.uk From noname9968 at gmail.com Mon Feb 18 11:49:02 2008 From: noname9968 at gmail.com (Alex) Date: Mon, 18 Feb 2008 19:49:02 +0300 Subject: How to get current module object In-Reply-To: References: <47B87C28.3030302@gmail.com> Message-ID: <47B9B6FE.50508@gmail.com> Gabriel Genellina wrote: > En Sun, 17 Feb 2008 16:25:44 -0200, Alex escribi?: > >> Can I get reference to module object of current module (from which the >> code is currently executed)? I know __import__('filename') should >> probably do that, but the call contains redundant information (filename, >> which needs to be updated), and it'll perform unnecessary search in >> loaded modules list. >> >> It shouldn't be a real problem (filename can probably be extracted from >> the traceback anyway), but I wonder if there is more direct and less >> verbose way. >> > sys.modules[__name__] > That's what I've been searching for, thanks. By the way, I know it might be trivial question... but function and class namespaces have __name__ attribute too. Why is global one always returned? > Why do you want to get the module object? globals() returns the module > namespace, its __dict__, perhaps its only useful attribute... To pass it as a parameter to a function (in another module), so it can work with several modules ("plugins" for main program) in a similar manner. From terry at jon.es Sun Feb 17 11:41:19 2008 From: terry at jon.es (Terry Jones) Date: Sun, 17 Feb 2008 17:41:19 +0100 Subject: flattening a dict In-Reply-To: Your message at 04:51:37 on Sunday, 17 February 2008 References: <36e90615-f6fe-4b39-b8a8-eb4d28583a58@j28g2000hsj.googlegroups.com> <09c2d0ff-f5f5-4879-9808-4768f60d6a51@28g2000hsw.googlegroups.com> <28cc2bbf-bb1d-4376-862b-b31fe140e193@v3g2000hsc.googlegroups.com> Message-ID: <18360.25519.160393.223279@jon.es> >>>>> "Arnaud" == Arnaud Delobelle writes: Arnaud> BTW, I keep using the idiom itertools.chain(*iterable). I guess Arnaud> that during function calls *iterable gets expanded to a tuple. Arnaud> Wouldn't it be nice to have an equivalent one-argument function Arnaud> that takes an iterable of iterables and return the 'flattened' Arnaud> iterable? This reminds me of a function I wrote a while back that iterates over all its arguments, even calling passed functions and iterating over their results. I knew *even less* about Python then than I do now; please set flamethrowers to "Constructive Criticism". http://www.fluidinfo.com/terry/2007/05/07/iteranything/ Terry From tmp1 at viltersten.com Thu Feb 28 23:38:04 2008 From: tmp1 at viltersten.com (K Viltersten) Date: Fri, 29 Feb 2008 05:38:04 +0100 Subject: SV: Running test01.py under Windows (basic level) In-Reply-To: References: <62os33F2352veU1@mid.individual.net> Message-ID: <62pfi6F244l0bU1@mid.individual.net> >> def bloppA (): >> print "a very advanced piece of code" > > go to File -> Open, open your saved file, > and use the Run menu (or press F5). When i try that i get this. >>> ====== RESTART ======= >>> And nothing more. Do i use wrong "print"?! -- Regards Konrad Viltersten -------------------------------- sleep - a substitute for coffee for the poor ambition - lack of sense to be lazy From zentraders at gmail.com Fri Feb 15 13:55:47 2008 From: zentraders at gmail.com (Zentrader) Date: Fri, 15 Feb 2008 10:55:47 -0800 (PST) Subject: Floating point bug? References: <6eba298e-6888-462a-afa7-54fae02c3dce@y5g2000hsf.googlegroups.com> <61ibo1F1uqso2U1@mid.uni-berlin.de> <188be6e9-bc05-4a72-924b-1de184980002@n58g2000hsf.googlegroups.com> Message-ID: <9b166b3d-89df-4f26-956a-abbd391167e7@i12g2000prf.googlegroups.com> I disagree with this statement But that doesn't change the fact that it will expose the same rounding-errors as floats do - just for different numbers. The example used has no rounding errors. For anything less that 28 significant digits it rounds to 1.0. With floats 1.0/3 yields 0.33333333333333331<-- on my machine. Also you can compare two decimal.Decimal() objects for equality. With floats you have to test for a difference less than some small value. BTW, a college professor who also wrote code for a living made this offhand remark "In general it is best to multiply first and then divide." Good general advice. From ptmcg at austin.rr.com Fri Feb 22 12:31:53 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 22 Feb 2008 09:31:53 -0800 (PST) Subject: Simple - looking for a way to do an element exists check.. References: Message-ID: <4f394676-0957-4d68-b9e1-6a2d8ff22e4a@d21g2000prf.googlegroups.com> On Feb 22, 11:20?am, rh0dium wrote: > Hi all, > > I have a simple list to which I want to append another tuple if > element 0 is not found anywhere in the list. > > element = ?('/smsc/chp/aztec/padlib/5VT.Cat', > ? '/smsc/chp/aztec/padlib', > ? '5VT.Cat', (33060)) > > element1 = ?('/smsc/chp/aztec/padlib/5VT.Cat2', > ? '/smsc/chp/aztec/padlib', > ? '5VT.Cat2', (33060)) > > a = ?[ ('/smsc/chp/aztec/padlib/5VT.Cat', > ? '/smsc/chp/aztec/padlib', > ? '5VT.Cat', (33060)), > ?('/smsc/chp/aztec/padlib/padlib.TopCat%', > ? '/smsc/chp/aztec/padlib', > ? 'padlib.TopCat%', (33204)), > ?('/smsc/chp/aztec/padlib/Regulators.Cat%', > ? '/smsc/chp/aztec/padlib', > ? 'Regulators.Cat%', (33204))] > > So my code would look something like this. > > found = False > for item in a: > ? if item[0] == element[0] > ? ? found = True > ? ? break > if not found: > ? a.append(element) > > But this is just ugly - Is there a simpler way to interate over all > items in a without using a found flag? > > Thanks Well, that's what I get for typing before thinking... If the remaining items in each element tuple are the same for any given element[0], then just use a set. aset = set(a) for element in list_of_new_element_tuples: aset.add(element) -- Paul From siona at chiark.greenend.org.uk Tue Feb 19 11:42:58 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 19 Feb 2008 16:42:58 +0000 (GMT) Subject: Linux/Python Issues References: <15a5dab0-02b7-49bb-9a3a-7883c6bd424b@i29g2000prf.googlegroups.com> Message-ID: wrote: >CNR, which is now free, is absolutely marvelous when it's got what you >need. If Python2.5 were in the warehouse, I'd have clicked, gone to >make a cup of coffee and the appropriate icon would be on my desktop >when I came back. If I were Python.org I'd not consider anything ready >for release until it was in the warehouse. Er, so how is it supposed to get into the warehouse if it's not first released from python.org ? -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From castironpi at gmail.com Sat Feb 23 16:39:17 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 23 Feb 2008 13:39:17 -0800 (PST) Subject: @synchronized dect'r &c. References: <0f6f2afe-baf1-4e7f-b8fb-859147636648@m23g2000hsc.googlegroups.com> Message-ID: <3b41fefe-899c-435f-8bca-c282e923390b@b29g2000hsa.googlegroups.com> Corrections. Typographical error in the implementation of #1. def synchronized( func ): def presynch( *ar, **kwar ): with _synchlock: lock= _synchhash.setdefault( func, allocate_lock() ) with lock: return func( *ar, **kwar ) return presynch On footnote #4, one might need a vector of jump addresses, one for each context in which the word might be modified. Yes, this involves a miniature "many small" design in actual hardware memory, and definitely opens some doors to faster processing. As such, it may not be the best "first" structural element in paralell off-loading, but it's a good one. And yes, it's specialty RAM, for which RAM may not even be the right place. If a few KB of it is enough, just bump it up next to the cache, which may make for shorter cycles on the jump-back later. You probably don't want to be setting the instruction pointer from a KB's worth of addresses, so there's probably an extra cycle involved in setting the jump register, halting the IP, and signalling a jump. Interrupts may be suited too. Does the OS need to provide an API before a compiler can make use of it? On #4, the signatures func( self, locks ) vs. func( locks, self ) is open: just if you sometimes want locks to be the second parameter, and other times the first, as for non-class-member functions, there will be two methods, or a parameter to signal the difference. From deets at nospam.web.de Sat Feb 16 05:55:04 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 16 Feb 2008 11:55:04 +0100 Subject: Where can I get the module MyUtils? In-Reply-To: <4aed89a3-95d4-4ee8-96c2-74556abe17ef@s37g2000prg.googlegroups.com> References: <4aed89a3-95d4-4ee8-96c2-74556abe17ef@s37g2000prg.googlegroups.com> Message-ID: <61ntodF20i8ouU1@mid.uni-berlin.de> Python_Doctor schrieb: > I inherited a piece of python code which imports "MyUtils" i.e. it has > a line: > > import MyUtils > > When I execute the code I get: > > ImportError: No module named MyUtils > > I assume the code is looking for another module called MyUtils.py. Is > this a standard Python module? Where can I download this module from? How large are the chances that something called "MyUtils" is a standard-module? And if it were - you wouldn't miss it, wouldn't you? I suggest you ask the one you inherited the code from - it's mosp probably his/hers. Diez From bbxx789_05ss at yahoo.com Sun Feb 17 20:21:16 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Sun, 17 Feb 2008 17:21:16 -0800 (PST) Subject: Tkinter Confusion References: <13044921-c8bc-4101-a98a-9fb0c0dadad9@n77g2000hse.googlegroups.com> Message-ID: <49315903-ca49-4bb6-ae68-658bc3fb6355@n58g2000hsf.googlegroups.com> On Feb 17, 12:36?pm, MartinRineh... at gmail.com wrote: > Everything I've read about Tkinter says you create your window and > then call its mainloop() method. But that's not really true. This is > enough to launch a default window from the console: > > >>>from Tkinter import * > >>>foo = Tk() > You shouldn't care what happens in an interactive python session. In fact, you can take years off your life trying to figure out why the output of an interactive session is different from the output of a python program. Here is how to create a basic window with one widget: import Tkinter as tk root = tk.Tk() label = tk.Label(root, text='hello world') label.pack() #makes widget visible root.mainloop() Adding in some more details: import Tkinter as tk root = tk.Tk() root.geometry('600x400') root.config(background='red') label = tk.Label(root, text='hello world', background='gray') label.pack() #makes widget visible root.mainloop() > Google's great, but it has no truth meter. Do I inherit from Frame? A frame is used to group widgets. You can have multiple frames each containing a group of widgets. That will allow you to place the group as a whole at a specific location in the window. Here's how to use frames to organize widgets: import Tkinter as tk root = tk.Tk() root.geometry('600x400') root.config(background='red') frame1 = tk.Frame(root) label1 = tk.Label(frame1, text='hello world', background='gray') label2 = tk.Label(frame1, text='goodbye', background='gray') label1.pack() #makes label visible label2.pack() #makes label visible frame1.pack(side=tk.BOTTOM) #makes frame visible frame2 = tk.Frame(root) label3 = tk.Label(frame2, text='yes', background='yellow') label4 = tk.Label(frame2, text='no', background='yellow') label5 = tk.Label(frame2, text='maybe', background='yellow') label3.pack() label4.pack() label5.pack() frame2.pack(side=tk.TOP) frame3 = tk.Frame(root) label6 = tk.Label(frame3, text='a', background='blue') label7 = tk.Label(frame3, text='b', background='blue') label8 = tk.Label(frame3, text='c', background='blue') label6.pack() label7.pack() label8.pack() frame3.pack(side=tk.LEFT) root.mainloop() > Do I use > Tk() or toplevel()? (Support for both and if a cogent explanation of > the differences exists, I didn't find it.) > Tk() for you first window; Toplevel() for any additional windows you want to open: import Tkinter as tk root = tk.Tk() root.geometry('300x200+50+50') #+x+y positions window root.config(background='red') label = tk.Label(root, text='hello world', background='gray') label.pack() window2 = tk.Toplevel() window2.geometry('300x200+400+50') root.mainloop() From spradml at gmail.com Sun Feb 17 04:59:15 2008 From: spradml at gmail.com (Pradnyesh Sawant) Date: Sun, 17 Feb 2008 15:29:15 +0530 Subject: xmltramp with python2.(4-5) In-Reply-To: <41355cfe-226b-4cf9-bb11-bf3479144d31@e10g2000prf.googlegroups.com> References: <41355cfe-226b-4cf9-bb11-bf3479144d31@e10g2000prf.googlegroups.com> Message-ID: <20080217095915.GC24617@debian> On 22:51, 16Feb2008, John Machin wrote: > On Feb 17, 5:40 pm, Pradnyesh Sawant wrote: > > fire up python2.4 interactive prompt > do this: > import sys; sys.path > import xmltramp; xmltramp.__file__ > > then fire up python2.5 interactive prompt > do this: > import sys; sys.path Hey, thanks a lot for that reply. it made me realise that xmltramp was something that is there in '/usr/lib/python2.4/site-packages/xmltramp.pyc' (a site-package for 2.4), and is hence not available for 2.5 it also showed me that I had _not_ installed it using apt for debian. unforutnately I dunno where I had got it from, and searching online didn't give me the result I wanted. anyways, thanks for leading me in the proper direction :) > > If that doesn't give you enough to nut out where xmltramp is and hence > why it's on one sys.path and not on the other, come back with the full > output from the above (including the info that python prints that > will tell us helpful things like what platform you are on) > > -- > http://mail.python.org/mailman/listinfo/python-list -- warm regards, Pradnyesh Sawant -- We are not just our behaviour. We are the person managing our behaviour. --The One Minute Manager -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From dblubaugh at belcan.com Fri Feb 1 12:52:10 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Fri, 1 Feb 2008 12:52:10 -0500 Subject: MyHDL project for FPGA development! In-Reply-To: <86380fd30802010813r7f46cd3tfc01995750cced21@mail.gmail.com> References: <27CC3060AF71DA40A5DC85F7D5B70F380239F9AE@AWMAIL04.belcan.com> <86380fd30802010813r7f46cd3tfc01995750cced21@mail.gmail.com> Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F380244BFA1@AWMAIL04.belcan.com> Dan, Thank you very much for your reply. My Master's thesis is for Wright State University and is of the following nature: I am currently engaged with a Masters project, that utilizes a linear array of isotropic sensors, or in my case electromagnetic antennas. I am trying to develop a specialized Multidimensional FFT processor, that can determine the angle of arrival and frequency content of a perceived target with respect to the position of the linear array. I should further state that this Multidimensional FFT processor is currently of only two dimensions. Therefore, the MDFFT will only have a result of frequency value versus angle of arrival of the target with respect to the position of the linear array. There is a great deal of mathematics that are involved (SciPy), especially considering that in order to model the two-dimensional signal of the linear sensor array, I have to utilize concepts borrowed from differential geometry. This is why I will need to utilize a toolset like SciPy with python. I would still like to include the ImpulseC environment, since the environment does provide an interesting connection between FPGA hardware and software running on embedded processors ,such as the Power PC on Xilinx FPGAS. I believe that a marriage between Python, ImpulseC, MyHDL, SciPy, Gene Expression Programming, and GNU Plot will develop into a very interesting and powerful algorithm development environment for FPGAS. I will also need a way to develop floating-point hardware, since I will need to have the dynamic range of floating-point in order to determine the angle of arrival of targets placed many miles away from the linear sensor array. This is why Impulse C should still be considered, since they provide the ability of generating efficient floating-point hardware. I have to go now, since I have to report for my employment duties. In conclusion, I would very much to continue development for a Python, Scipy, MyHDL combined. If there are any more questions, Dan, please contact me as soon as possible. Respectfully, David ________________________________ From: Dan Fabrizio [mailto:dfabrizio51 at gmail.com] Sent: Friday, February 01, 2008 11:14 AM To: Blubaugh, David A. Subject: Re: MyHDL project !!!!! David, Let's start by discussing your masters thesis subject in more detail. We can take a project from conception to hardware using MyHDL, NumPy and SciPy. Maybe you could use this project as a proof for your thesis showing this methodology warrants consideration compared other ASIC/FPGA flows. Let's discuss some of your ideas and decide how to proceed. Dan On Feb 1, 2008 10:43 AM, Blubaugh, David A. wrote: Dan, I would be honored to start a project such as that in mind. How do we begin ?????? David Blubaugh -----Original Message----- From: chewie54 [mailto:dfabrizio51 at gmail.com] Sent: Thursday, January 31, 2008 9:34 PM To: python-list at python.org Subject: Re: Will Python on day replaceMATLAB????????????????????????????????????????????????????? > I have been evaluating the python environment ever more closer. I > believe I can interface python with a development environment known as > the ImpulseC environment. The ImpulseC environment develops C to VHDL > for FPGA development. I would especially love to interface Python > with ImpulseC and the graphing capabilities of GNU Plot and SciPy in > order to recreate a VHDL development environment that will be just as > capable as a $50,000 dollar Matlab to VHDL toolbox. This is also a > part of my Masters thesis. Is anyone willing to help in this endeavor????? > > David Blubaugh > Why not use MyHDL which is written in Python and translates to Verilog. I assume ImpulseC is a commercial product and costs a log. MyHDL is free. If you have any interests in combining MyHDL with SciPy and NumPy I would be interested in getting involved. Dan Fabrizio This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Fri Feb 8 19:23:55 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 08 Feb 2008 19:23:55 -0500 Subject: Why not a Python compiler? In-Reply-To: <13qp5a02t36def9@corp.supernews.com> References: <28eead2f-a40c-414b-bd3d-a941f8a851a2@d70g2000hsb.googlegroups.com> <81339c25-f9b6-47a1-941e-8ae39c35773c@e6g2000prf.googlegroups.com> <98a1bc2d-290b-4b6d-8a3d-eda7666d2b8b@l1g2000hsa.googlegroups.com> <13qmtu5j1b1p6a2@corp.supernews.com> <8763x0fix1.fsf@mulj.homelinux.net> <13qp5a02t36def9@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2008-02-08, Arnaud Delobelle wrote: > >>> the compiler could do little else except translate it to something >>> like: >>> >>> (python:add a b) >> [snip more interesting considerations about compiling python] >> >> Please get back on topic. This discussion is about parsecs and >> wookies now. > > What's a "wookie" a unit of? > A wookie is someone who's onwy just joined a team and hasn't pwayed vewy much. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From sean at chittenden.org Wed Feb 27 14:42:59 2008 From: sean at chittenden.org (Sean Chittenden) Date: Wed, 27 Feb 2008 11:42:59 -0800 Subject: refreshing the cache time of a key In-Reply-To: <910313af0802270417s758f7962h656310da1b11e62@mail.gmail.com> References: <910313af0802270417s758f7962h656310da1b11e62@mail.gmail.com> Message-ID: <1F569950-0E61-4F7F-AB6C-42D819B9CAC9@chittenden.org> > is it possible to refresh the cache time of a key with out having > to retrieving the cached data and storing it back in memcache .. for > example if a data is cached for > 1 hour and at the 50th minute from the time this data has been > cached i want to store it in the cache for 1 more hour ..is > there a function to refresh the cache time by knowing the key of > data with out having to do get and set > i.e > data=mc.get(key) > mc.set(key,data,3600) # 1 more hour It's not possible with the current code base. I posted a patch a few years back that did this.... here we go: http://lists.danga.com/pipermail/memcached/2004-November/000880.html It should be easy to apply the patch by hand if it fails to apply cleanly out of the gate. FWIW, I find this functionality invaluable. See the post for details. -sc -- Sean Chittenden sean at chittenden.org http://sean.chittenden.org/ From AWasilenko at gmail.com Sat Feb 16 11:35:38 2008 From: AWasilenko at gmail.com (Adam W.) Date: Sat, 16 Feb 2008 08:35:38 -0800 (PST) Subject: Easy PIL question Message-ID: <6cd3f2f9-a65f-408f-a40d-6ef4036a2b41@q70g2000hsb.googlegroups.com> I know there is an easy way to do this, but I can't figure it out, how do I get the color of a pixel? I used the ImageGrab method and I want to get the color of a specific pixel in that image. If you know how to make it only grab that pixel, that would also be helpful. Basically I'm trying to make a: if pixel == color: do_this() else: pass And have it do this as fast as my pc can handle (that is why only grabbing 1px would be helpful) From lizhongan at gmail.com Fri Feb 22 02:22:20 2008 From: lizhongan at gmail.com (zaley) Date: Thu, 21 Feb 2008 23:22:20 -0800 (PST) Subject: Is there a open souce IDE writen by C( C++) or partly writen by C( C++)? References: <42a838b9-2023-4cbf-bc53-e7ac5f4accbc@i7g2000prf.googlegroups.com> <47BE6D27.7000305@behnel.de> Message-ID: My project need a simple scripts debugger . I hope I can find something instructive Stefan Behnel ??? > zaley wrote: > > Is there a open souce IDE writen by C( C++) or partly writen by C( C+ > > +)? > > Tons of them. What do you want to do with it? > > Stefan From gagsl-py2 at yahoo.com.ar Fri Feb 15 18:28:04 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 15 Feb 2008 21:28:04 -0200 Subject: Assignment saves time? References: <87bq6iphua.fsf@mulj.homelinux.net> <45fe7ed2-0cd6-4287-a81c-63749041e8d0@e23g2000prf.googlegroups.com> <8e3ae780-75aa-4ba0-a19a-ddc91664b888@o77g2000hsf.googlegroups.com> Message-ID: En Fri, 15 Feb 2008 18:51:19 -0200, escribi?: > I ran it in an interactive python shell, which might have made a > difference. > > import timeit > time1=timeit.Timer('s=len(li); s==1000', 'li=range(1000)') > time2=timeit.Timer('len(li)==1000', 'li=range(1000)') > store=min(time1.repeat(5)) > call=min(time2.repeat(5)) > store=min(min(time1.repeat(5)),store) > call=min(min(time2.repeat(5)),call) > store > 0.25531911849975586 > call > 0.25700902938842773 > > The difference is small enough to be insignificant, but I am curious > how it's possible and why it happened. It's more likely a reflection > of how I timed it than anything else, isn't it? Yes, I think it's an artifact of how you measured it. I've tried this: import timeit time1=timeit.Timer('s=len(li); s==1000', 'li=range(1000)') r1 = time1.repeat(5) print 'store', min(r1), r1 time2=timeit.Timer('len(li)==1000', 'li=range(1000)') r2 = time2.repeat(5) print 'call', min(r2), r2 and got the expected results: store 0.336916842783 [0.33712636661922118, 0.34131209413486907, 0.33691684278309109, 0.33726828409755982, 0.34154312908484186] call 0.296055783626 [0.29648125669603265, 0.29605578362613105, 0 .29716346630647195, 0.29883546651878934, 0.29798368228364236] -- Gabriel Genellina From grante at visi.com Tue Feb 26 14:25:02 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 26 Feb 2008 19:25:02 -0000 Subject: How about adding rational fraction to Python? References: <1bc9bba7-dc7f-4cfe-8e1c-fa5901c9f556@n77g2000hse.googlegroups.com> <97f30679-483d-4751-9a6e-0858b36eb426@d4g2000prg.googlegroups.com> <649ac8a9-ae09-4e9b-85c2-f37043af21fd@28g2000hsw.googlegroups.com> <0d1955fc-762c-44e1-a5d8-372c71458455@p25g2000hsf.googlegroups.com> <36204e6f-0d82-449b-8ca5-c819ace9a55a@p73g2000hsd.googlegroups.com> <9503b14b-7bd5-42b4-b3f7-673d0ebd7feb@c33g2000hsd.googlegroups.com> <602ac27c-4aaa-49b2-bee2-1e0e0c705983@i7g2000prf.googlegroups.com> <13s8j1tglqpth80@corp.supernews.com> <6aWdnZtVGbEd01nanZ2dnUVZ_q_inZ2d@comcast.com> Message-ID: <13s8pse1m27od78@corp.supernews.com> On 2008-02-26, Jeff Schwab wrote: > Grant Edwards wrote: > >> I guess it must depend on where you went to shool. > > Temple Israel. You? Good one. :) -- Grant Edwards grante Yow! Do you think the at "Monkees" should get gas on visi.com odd or even days? From krishnakirti at gmail.com Tue Feb 26 16:23:44 2008 From: krishnakirti at gmail.com (Krishna Kirti Das) Date: Tue, 26 Feb 2008 13:23:44 -0800 (PST) Subject: Windows System Administration: State of the Art on Python? Message-ID: <590cef15-941a-4f65-8acb-d3023a2dc08a@d21g2000prf.googlegroups.com> I am a long-time user of Perl who comes to you in peace and is evaluating different scripting languages for use as a scripting platform for system administrators on the Windows platform. Perl already has many modules that allow sys admins and devolpers to do lots of things with the Windows OS, and I'm wondering what the state of the art is with Python and being able to control and administer a windows environment. In this regard, how does Python stand up against Perl? From asmodai at in-nomine.org Fri Feb 8 09:18:30 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Fri, 8 Feb 2008 15:18:30 +0100 Subject: Time conversion between UTC and local time In-Reply-To: <486ff322-dcb5-4903-a86d-178b8a4d5ce2@e10g2000prf.googlegroups.com> References: <486ff322-dcb5-4903-a86d-178b8a4d5ce2@e10g2000prf.googlegroups.com> Message-ID: <20080208141830.GL39133@nexus.in-nomine.org> -On [20080208 15:16], andreas.profous at googlemail.com (andreas.profous at googlemail.com) wrote: >What is an elegant way of getting the local time (considering DST - >daylight saving time) with that data? Perhaps using pytz might be the easiest way: http://pytz.sourceforge.net/ -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ But Time, keeps flowing like a river (on and on)... From martin at v.loewis.de Tue Feb 19 17:23:12 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 19 Feb 2008 23:23:12 +0100 Subject: Threads vs. continuations In-Reply-To: <061541c8-1f37-42bc-8041-170fee9707b4@h25g2000hsf.googlegroups.com> References: <061541c8-1f37-42bc-8041-170fee9707b4@h25g2000hsf.googlegroups.com> Message-ID: <47BB56D0.2010704@v.loewis.de> > I've been doing some thinking, and I've halfway convinced myself of > the following statement: that threads as implemented by Python (or > Java) are exactly equivalent to one-shot continuations in Scheme. Am > I right? No. In case of threads, progress can be made in an overlapping (concurrent), in case of Java even parallel fashion. In particular, if a thread blocks in a blocking operating system call (e.g. a network receive operation), other threads can continue. I believe this is not possible with continuations in Scheme. In more detail, threads as provided by the operating system underly a system scheduler: they can be preempted, they have priorities, and they may voluntarily block. All this is not possible with continuations. IOW, threads are more expressive than continuations. Regards, Martin From steve at holdenweb.com Thu Feb 21 18:47:42 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 21 Feb 2008 18:47:42 -0500 Subject: Inserting NULL values with pymssql In-Reply-To: <3F533E9AEFD4D343B5EA0E475321F21E03196D36@PDXEX01.webtrends.corp> References: <3F533E9AEFD4D343B5EA0E475321F21E03196D36@PDXEX01.webtrends.corp> Message-ID: Jayson Barley wrote: > I am attempting to insert NULL values into a database. I have tried to > do this in multiple ways without any success, see below, and haven't > been able to find anything through Google to help out. I am hoping that > I am just overlooking something or that it is a rookie mistake. Below is > a test I came up with to prove this. I am on Windows XP using Python 2.5 > and pymssql-0.8.0-py2.5. > > CREATE TABLE [dbo].[Test]( > [test] [varchar](50) NULL, > [inttest] [int] NULL > ) ON [PRIMARY] > > 1. > import pymssql > > TestDB = > pymssql.connect(host='Test',user='test',password='test',database='test') > cursor = TestDB.cursor() > query = """INSERT INTO test.dbo.test VALUES (?, ?);""" > cursor.execute(query,('','')) > Returns > > Traceback (most recent call last): > File "C:\Test\db_info\test.py", line 6, in > cursor.execute(query,('','')) > File "C:\Python25\lib\site-packages\pymssql.py", line 126, in execute > self.executemany(operation, (params,)) > File "C:\Python25\lib\site-packages\pymssql.py", line 152, in executemany > raise DatabaseError, "internal error: %s" % self.__source.errmsg() > pymssql.DatabaseError: internal error: None > > 2. > import pymssql > > TestDB = > pymssql.connect(host='Test',user='test',password='test',database='test') > cursor = TestDB.cursor() > query = """INSERT INTO test.dbo.test VALUES (?, ?);""" > cursor.execute(query,('',None)) > > Returns > > Traceback (most recent call last): > File "C:\Test\db_info\test.py", line 8, in > cursor.execute(query,('',None)) > File "C:\Python25\lib\site-packages\pymssql.py", line 126, in execute > self.executemany(operation, (params,)) > File "C:\Python25\lib\site-packages\pymssql.py", line 152, in executemany > raise DatabaseError, "internal error: %s" % self.__source.errmsg() > pymssql.DatabaseError: internal error: None > > 3. > import pymssql > > TestDB = > pymssql.connect(host='Test',user='test',password='test',database='test') > cursor = TestDB.cursor() > query = """INSERT INTO test.dbo.test VALUES (?, ?);""" > cursor.execute(query,('','NULL')) > Returns > > Traceback (most recent call last): > File "C:\Test\db_info\test.py", line 6, in > cursor.execute(query,('','NULL')) > File "C:\Python25\lib\site-packages\pymssql.py", line 126, in execute > self.executemany(operation, (params,)) > File "C:\Python25\lib\site-packages\pymssql.py", line 152, in executemany > raise DatabaseError, "internal error: %s" % self.__source.errmsg() > pymssql.DatabaseError: internal error: None > > I am wondering what I am missing that is preventing me from inserting a > NULL. I can perform the INSERT in Server Management Studio the problem > only exists in the Python script. If anyone can point me to a resource > that I may have missed or a flaw in my script I would really appreciate it. > What you want is two NULL data values as the second argument to execute(): cursor.execute(query,(None, None)) > I also forgot to mention that this... > > import pymssql > > TestDB = pymssql.connect(host='Test',user='test',password='test',database='test') > cursor = TestDB.cursor() > query = """INSERT INTO test.dbo.test (test) VALUES ('%s');""" > cursor.execute(query,(None)) > > works. While > That's a very naughty database module. It should complain, since you didn't provide a tuple as the second argument to execute(). > import pymssql > > TestDB = pymssql.connect(host='Test',user='test',password='test',database='test') > cursor = TestDB.cursor() > query = """INSERT INTO test.dbo.test (inttest) VALUES ('%d');""" > cursor.execute(query,(None)) > > doesn't work and returns > > Traceback (most recent call last): > File "C:\Test\db_info\test.py", line 6, in > cursor.execute(query,(None)) > File "C:\Python25\lib\site-packages\pymssql.py", line 126, in execute > self.executemany(operation, (params,)) > File "C:\Python25\lib\site-packages\pymssql.py", line 152, in executemany > raise DatabaseError, "internal error: %s" % self.__source.errmsg() > pymssql.DatabaseError: internal error: SQL Server message 245, severity 16, state 1, line 1: > Conversion failed when converting the varchar value '%d' to data type int. > DB-Lib error message 10007, severity 5: > General SQL Server error: Check messages from the SQL Server. I don't know what pymssql's paramstyle is, but I suspect it requires a "%s" far all parameters regardless of their data type. That's SQL Server complaining about the %d, pymssql having failed to recognize it as a parameter marker and passed it through to the engine. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From ilias at lazaridis.com Sat Feb 16 20:59:51 2008 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Sat, 16 Feb 2008 17:59:51 -0800 (PST) Subject: TRAC - Trac, Project Leads, Python, and Mr. Noah Kantrowitz (sanitizer) References: <3d40196b-b1c8-4e18-92f0-7ce5a5a38853__43679.3406880044$1203164550$gmane$org@u72g2000hsf.googlegroups.com> Message-ID: On 16 ???, 15:45, Steve Holden wrote: > Ilias Lazaridis wrote: > > [...]> Of course I'll not stay with trac, I'll leave the sinking ship, I've > > prepare long time ago to do so, step by step. An will migrate step by > > step away from trac and python - toward an own implementation based > > on... > > > perl and it's libraries. > > I'm sure you will find the Perl community much more welcoming and > receptive to your ideas about how open source projects should be run. The perl projects can decide themselfs if they like to adopt the most essential things: http://case.lazaridis.com/wiki/Project I do not analyze languages and communities anymore, thus there is no need for them to 'worry', e.g. that I attemp to transform them to an high evolutive language system. Ruby and Python were excellent for this (Ruby = weak puppets, Python = egoism driven). I'll just use perl until I've implemented my own language, around 2010 to 2011, which will be most possibly close to perl (or a perl extension, if technically possibly and no legal barriers with libraries). Perl is available in nearly every webserver, and has very nice a logical OO functionality (although it's not very good marketed, this OO part). And perl keeps you highly independent, you can work with simple systems, close to the OS. > > Really, I don't understand the need for python. And after fighting > > with some indenting within html templates, I dislike the whitespace- > > syntax-thing of python again. > > Fortunately, as you have realized, you have choices and are under no > compulsion to use any particular tool. As said above: python (essentially it's community in a wider scope) is an ideal domain to analyze how human egoism blocks evolution of technical systems. Thus, python is an important educational tool. > > Do it in perl, if you need something more 'pretty', do it in ruby, if > > you need something more 'serious' do it in java, if you have enough > > brain and time, do it in C++ from bottom up. > > And, apparently, do it in Python if you want to avoind running into > Ilias Lazaridis. No, I'll be bound to python for some time, a year or so. And good news: as I cannot post to the trac-user group, I'll post the topics to comp.lang.python. (you can thank the project lead of trac, his lack of courage is the reason that the developers get out of control) > I have to say your approach to IT systems seems somewhat pedestrian, The IT industry has failed to provide simple standards, systems. AI has failed to produce intelligent systems. So, maybe the IT industry is somewhat pedestrian, as its failure to control egoism has led to terrible software systems. Restarting from the beginning can give the impression of a "learning child". > but I wish you well in whatever it is you are trying to achieve. http://core.lazaridis.com/wiki/ActivityHistory > I hope you have a good set of asbestos (i.e. flame-proof) trousers. As said, the analysis phase is over. But even if not: I've 'survived' within comp.lang.lisp for some months http://groups.google.gr/group/comp.lang.lisp/browse_frm/thread/87980954f111e965/af5f19a1c8101a93?lnk=st&q=dynamite+and+teflon+ilias#af5f19a1c8101a93 I think no language community can be worser. - Btw: If you would adopt the open-source-processes to digital electronic design, we would work today still with 8086. http://case.lazaridis.com/wiki/ProjectLead . From http Wed Feb 27 00:41:16 2008 From: http (Paul Rubin) Date: 26 Feb 2008 21:41:16 -0800 Subject: How about adding rational fraction to Python? References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> Message-ID: <7x63wbez2b.fsf@ruckus.brouhaha.com> Mark Dickinson writes: > > So use: ?return sum(number_list) / float(len(number_list)) > > That makes it somewhat more explicit what you want. ?Otherwise > > But that fails for a list of Decimals... Again, that depends on what your application considers to be failure. Heck, int/int = float instead of decimal might be a failure. FWIW, I just checked Haskell: int/int is not allowed (compile time type error). There is an integer division function `div`, like Python's //, . that you can use if you want an integer quotient. If you want a floating or rational quotient, you have to coerce the operands manually. Explicit is better than implicit. From john.deas at gmail.com Fri Feb 8 04:29:26 2008 From: john.deas at gmail.com (John Deas) Date: Fri, 8 Feb 2008 01:29:26 -0800 (PST) Subject: Chinese character error Message-ID: <7355c3c6-343b-419e-9d01-cc48bb70283e@n20g2000hsh.googlegroups.com> Hi, I made a small script to recursively copy files from a directory tree to an exportDir only if they have an mp3 extension : a=os.walk(os.getcwd()) for root, dirs, files in a: for currFile in files: pathCurrFile=os.path.join(root, currFile) if mp3Reg.search(pathCurrFile): shutil.copy(pathCurrFile,exportDir) else: print pathCurrFile The problem is that I get stuck with files containing name in Chinese : Traceback (most recent call last): File "/cygdrive/c/Documents and Settings/vku/Mes documents/Ma musique/iTunes/i Tunes Music/script.py", line 21, in shutil.copy(pathCurrFile,exportDir) File "/usr/lib/python2.5/shutil.py", line 80, in copy copyfile(src, dst) File "/usr/lib/python2.5/shutil.py", line 46, in copyfile fsrc = open(src, 'rb') IOError: [Errno 2] No such file or directory: '/cygdrive/c/Documents and Setting s/vku/Mes documents/Ma musique/iTunes/iTunes Music/Podcasts/Learn Chinese - Chin esePod/785 Advanced - ????.mp3' I am using python on cygwin, so could this be the source of the error, and is there a way to fix this ? From http Fri Feb 22 00:39:35 2008 From: http (Paul Rubin) Date: 21 Feb 2008 21:39:35 -0800 Subject: Return value of an assignment statement? References: <6d945394-739e-4c47-ad71-faaab8f9d566@34g2000hsz.googlegroups.com> <5sudnTSXrZY0aCDanZ2dnUVZ_rKtnZ2d@comcast.com> <5MSdncSVGdGriCPanZ2dnUVZ_vPinZ2d@comcast.com> Message-ID: <7xskzlczxk.fsf@ruckus.brouhaha.com> Jeff Schwab writes: > So what is the "variable?" Or is Python the first HLL I've ever heard > of that didn't have variables? I don't know what other HLL's you use, but some languages don't even have mutable values. From mwilson at the-wire.com Mon Feb 4 09:10:21 2008 From: mwilson at the-wire.com (Mel) Date: Mon, 04 Feb 2008 09:10:21 -0500 Subject: type, object hierarchy? References: <814a05b4-6f13-4c86-8c68-a30da06ca093@b2g2000hsg.googlegroups.com> <2ba95819-0699-49c6-b7e9-96d54763be52@v17g2000hsa.googlegroups.com> <4a2fabf4-5a4d-4afc-a722-f2887da10d1f@q39g2000hsf.googlegroups.com> Message-ID: 7stud wrote: > On Feb 3, 10:28 pm, 7stud wrote: >> From the docs: >> >> issubclass(class, classinfo) >> Return true if class is a subclass (direct or indirect) of classinfo. > > > print issubclass(Dog, object) #True > print issubclass(type, object) #True > print issubclass(Dog, type) #False Python 2.5.1 (r251:54863, Oct 5 2007, 13:36:32) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> issubclass (object, type) False >>> isinstance (object, type) True From benhoyt at gmail.com Mon Feb 18 17:28:43 2008 From: benhoyt at gmail.com (benhoyt) Date: Mon, 18 Feb 2008 14:28:43 -0800 (PST) Subject: Double underscores -- ugly? Message-ID: Hi guys, I've been using Python for some time now, and am very impressed with its lack of red tape and its clean syntax -- both probably due to the BDFL's ability to know when to say "no". Most of the things that "got me" initially have been addressed in recent versions of Python, or are being addressed in Python 3000. But it looks like the double underscores are staying as is. This is probably a good thing unless there are better alternatives, but ... Is it just me that thinks "__init__" is rather ugly? Not to mention "if __name__ == '__main__': ..."? I realise that double underscores make the language conceptually cleaner in many ways (because fancy syntax and operator overloading are just handled by methods), but they don't *look* nice. A solution could be as simple as syntactic sugar that converted to double underscores behind the scenes. A couple of ideas that come to my mind (though these have their problems too): def ~init(self): # shows it's special, but too like a C++ destructor def +init(self): # a bit too additive :-) defop add(self, other): # or this, equivalent to "def __add__" def operator add(self, other): # new keyword, and a bit wordy Has anyone thought about alternatives? Is there a previous discussion on this I can look up? Cheers, Ben. From usenet at ionline.dk Wed Feb 27 13:45:53 2008 From: usenet at ionline.dk (ndlarsen) Date: Wed, 27 Feb 2008 19:45:53 +0100 Subject: Print to end of line in a terminal Message-ID: <47c5afe4$0$90273$14726298@news.sunsite.dk> Hey. This might seem as a arbitrary question to some. Anyway, I'm wondering how I go about printing text to the end of a line in a terminal/console. I've been googling it for a few days without any success. Any suggestions will be greatly appreciated. Regards ndlarsen From mal at egenix.com Wed Feb 20 11:05:18 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Wed, 20 Feb 2008 17:05:18 +0100 Subject: Handling locked db tables... In-Reply-To: <6768beab-566e-4d0e-94c9-a4def273d467@m23g2000hsc.googlegroups.com> References: <6768beab-566e-4d0e-94c9-a4def273d467@m23g2000hsc.googlegroups.com> Message-ID: <47BC4FBE.5050705@egenix.com> On 2008-02-20 16:24, breal wrote: > I have a db table that holds a list of ports. There is a column > in_use that is used as a flag for whether the port is currently in > use. When choosing a port the table is read and the first available > port with in_use = 0 is used, updated to in_use = 1, used, then > updated to in_use = 0. I am using MySQLdb and want to make sure I am > locking the table when doing reads, writes, updates since there will > be several instances of my program looking for available ports > simultaneously. > > When I run a "lock table mytable read" I can do all of my > transactions. But, when another cursor then tries to do the read I > get an error unless the first process has been completed... unlocking > the tables. How is this handled generally? This is normal database locking behavior. If you do an update to a table from one process, the updated row is locked until the transaction is committed. If another process wants to access that row (even if only indirectly, e.g. a select that does a query which includes the data from the locked row), that process reports a database lock or times out until the lock is removed by the first process. The reason is simple: you don't want the second process to report wrong data, since there's still a chance the first process might roll back the transaction. Most modern database allow row-level locking. I'm not sure whether MySQL supports this. SQLite, for example, only support table locking. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Feb 20 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From rw at smsnet.pl Fri Feb 22 13:42:40 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Fri, 22 Feb 2008 19:42:40 +0100 Subject: n00b with urllib2: How to make it handle cookie automatically? References: Message-ID: <87pruorfxb.fsf@merkury.smsnet.pl> est writes: > Hi all, > > I need urllib2 do perform series of HTTP requests with cookie from > PREVIOUS request(like our browsers usually do ). Many people suggest I > use some library(e.g. pycURL) instead but I guess it's good practise > for a python beginner to DIY something rather than use existing tools. > > So my problem is how to expand the urllib2 class > > from cookielib import CookieJar > class SmartRequest(): > cj=CookieJar() > def __init__(self, strUrl, strContent=None): > self.Request = urllib2.Request(strUrl, strContent) > self.cj.add_cookie_header(self.Request) > self.Response = urllib2.urlopen(Request) > self.cj.extract_cookies(self.Response, self.Request) > def url > def read(self, intCount): > return self.Response.read(intCount) > def headers(self, strHeaderName): > return self.Response.headers[strHeaderName] > > The code does not work because each time SmartRequest is initiated, > object 'cj' is cleared. How to avoid that? > The only stupid solution I figured out is use a global CookieJar > object. Is there anyway that could handle all this INSIDE the class? > > I am totally new to OOP & python programming, so could anyone give me > some suggestions? Thanks in advance Google for urllib2.HTTPCookieProcessor. HTH, Rob From bignose+hates-spam at benfinney.id.au Mon Feb 18 07:31:15 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 18 Feb 2008 23:31:15 +1100 Subject: decode Numeric Character References to unicode References: Message-ID: <87skzqla3w.fsf@benfinney.id.au> 7stud writes: > For instance, an 'o' with umlaut can be represented in three > different ways: > > '&' followed by 'ouml;' > '&' followed by '#246;' > '&' followed by '#xf6;' The fourth way, of course, is to simply have '?' appear directly as a character in the document, and set the correct character encoding. (Hint: UTF-8 is an excellent choice for "the correct character encoding", if you get to choose.) -- \ ?With Lisp or Forth, a master programmer has unlimited power | `\ and expressiveness. With Python, even a regular guy can reach | _o__) for the stars.? ?Raymond Hettinger | Ben Finney From michael.pearmain at tangozebra.com Tue Feb 12 05:21:49 2008 From: michael.pearmain at tangozebra.com (Mike P) Date: Tue, 12 Feb 2008 02:21:49 -0800 (PST) Subject: CSV Reader References: <43a3a0d8-9425-4bc5-90d3-894fe980d3f7@s19g2000prg.googlegroups.com> <4b1e691a-53ff-4cee-8e15-5bf17f2b56ef@i12g2000prf.googlegroups.com> Message-ID: I did just try to post, but it doesn't look like it has appeared? I've used your advice Andrew and tried to use the CSV module, but now it doesn't seem to pick up the startswith command? Is this because of the way the CSV module is reading the data in? I've looked into the module description but i can't find anything that i hould be using? Can anyone offer an advice? Cheers again Mike working_CSV = "//filer/common/technical/Research/E2C/Template_CSV/ DFAExposureToConversionQueryTool.csv" save_file = "//filer/common/technical/Research/E2C/Template_CSV/ CSV_Data2.csv" start_line=False import csv reader = csv.reader(open(working_CSV, "rb")) writer = csv.writer(open(save_file, "wb")) for row in reader: if not start_line and record.startswith("'Transaction ID'"): start_line=True if start_line: print row writer.writerows(rows) #writer.close() From arnodel at googlemail.com Tue Feb 26 17:00:03 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 26 Feb 2008 14:00:03 -0800 (PST) Subject: How about adding rational fraction to Python? References: <0d1955fc-762c-44e1-a5d8-372c71458455@p25g2000hsf.googlegroups.com> <36204e6f-0d82-449b-8ca5-c819ace9a55a@p73g2000hsd.googlegroups.com> <9503b14b-7bd5-42b4-b3f7-673d0ebd7feb@c33g2000hsd.googlegroups.com> <602ac27c-4aaa-49b2-bee2-1e0e0c705983@i7g2000prf.googlegroups.com> <1204034122.3318.3.camel@aalcdl07.lib.unc.edu> <874pbvvhu1.fsf@mulj.homelinux.net> <13s927o65an9b58@corp.supernews.com> Message-ID: On Feb 26, 9:47?pm, Steven D'Aprano wrote: > On Tue, 26 Feb 2008 11:43:56 -0500, D'Arcy J.M. Cain wrote: > > Integer division means integer result to me in a very real sense. > > So, when you have five children over for a birthday party, and one cake, > do you say "Sorry kids, no cake for you: one cake divided by five is > zero"? > > Of course you do, you big meanie. I think you catered for my 12th > birthday party. Whereas I bet you would be able to share the cake equally and each child would get 0.20000000000000001 of a cake :) Or perhaps it would be better to have 2**n guests... Or maybe one should think of the cake as 1.0 cake, as experience shows that cakes can be cut... -- Arnaud From steve at holdenweb.com Sat Feb 9 00:29:35 2008 From: steve at holdenweb.com (Steve Holden) Date: Sat, 09 Feb 2008 00:29:35 -0500 Subject: Help Wanted (Volunteer(s)) Message-ID: The Job Board needs you, please see http://pyfound.blogspot.com/2008/02/help-needed-with-python-job-board.html regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From tjreedy at udel.edu Mon Feb 25 15:42:51 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 25 Feb 2008 15:42:51 -0500 Subject: Using lambda [was Re: Article of interest: Python pros/cons fortheenterprise] References: <47bd4a24$0$25225$426a74cc@news.free.fr><036e93e6-5840-4a3c-8642-67a0a9ec44f2@i7g2000prf.googlegroups.com><784ec210-f389-4a15-b458-961100de9103@v3g2000hsc.googlegroups.com><5MSdncqVGdEXiSPanZ2dnUVZ_vPinZ2d@comcast.com><7xwsoxd00c.fsf@ruckus.brouhaha.com><7xmyprtay1.fsf@ruckus.brouhaha.com><88qdnQR0a7V7Rl3anZ2dnUVZ_rqlnZ2d@comcast.com><7xmyprf3ef.fsf@ruckus.brouhaha.com> <13s5kclk4maa584@corp.supernews.com> Message-ID: "Steven D'Aprano" wrote in message news:13s5kclk4maa584 at corp.supernews.com... | On Sun, 24 Feb 2008 21:13:08 -0500, Terry Reedy wrote: | | > | I even use "named anonymous functions" *cough* by assigning lambda | | > functions to names: | > | | > | foo = lambda x: x+1 | > | > Even though I consider the above to be clearly inferior to | > | > def foo(x): return x+1 | > | > since the latter names the function 'foo' instead of the generic | > ''. | | Absolutely. If foo() was a function that the user would see, I would | certainly use the def form to create it. | | But in a situation like this: | | | def parrot(x, y, z, func=None): | if func is None: | func = lambda x: x+1 | return func(x+y+z) Since functions are constants with respect to code attribute, you might as well condense that to def parrot(x,y,z, func = lambda xyz: xyz+1): return func(x+y+z) Then you can claim some actual space saving. | I don't see any advantage to writing it as: | | def parrot(x, y, z, func=None): | if func is None: | def func(x): return x+1 | return func(x+y+z) Good habit? Don't mislead the newbies ;-? tjr From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Feb 14 09:26:02 2008 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 14 Feb 2008 15:26:02 +0100 Subject: Running CGI from within CGI In-Reply-To: <703e55c2-00c0-43a6-9f67-988994ac44b9@e23g2000prf.googlegroups.com> References: <703e55c2-00c0-43a6-9f67-988994ac44b9@e23g2000prf.googlegroups.com> Message-ID: <47b44f3e$0$29332$426a34cc@news.free.fr> rodmc a ?crit : > I am new to using Python as a CGI platform, so please excuse me if > this is a dumb question. > > Anyway I have written a series of web forms (with Python scripts) > which allow the user input but also retrieve data from a database. The > data entry stage works fine however retrieving data is a little more > tricky. However I need to find a way to call the scripts directly from > within other CGI's. At present when I go to the next page I call the > normal HTML page as below: > > p = open('somefile.html') > some = p.read() > p.close() > print some > > > However I would like to execute a script instead so calling for > example myscript.py - thus populating the existing forms with data. > This does not seem to work when I modify the above method. Is there > another way to do it? Thanks in advance. The QuickAndDirtyWay(tm) would be to use execfile IIRC. But since you *don't* want to do it that way, the best thing to do would be to factor out common code into functions in a distinct module (or in as many modules as needed), then rewrite your cgi scripts so they import the relevant modules and call the appropriate functions. And while we're at it, I'd greatly recommand giving a look at the various templating packages around (may I recommand Mako ?) and the FormEncode package for HTTP forms conversion/validation ? HTH From wolf_tracks at invalid.com Sun Feb 17 22:33:44 2008 From: wolf_tracks at invalid.com (W. Watson) Date: Mon, 18 Feb 2008 03:33:44 GMT Subject: Pmw Use and Grayson's Book Message-ID: I don't have Grayson's Tkinter book, but I see he uses something called Pmw. Why is it needed with Tkinter? -- Wayne Watson (Nevada City, CA) Web Page: From jzgoda at o2.usun.pl Tue Feb 19 04:32:32 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Tue, 19 Feb 2008 10:32:32 +0100 Subject: Garbage collection In-Reply-To: References: Message-ID: Duncan Booth napisa?(a): > Pretty much. If you have a __del__ method on an object then in the worst > case the only thing that can be guaranteed is that it will be called zero, > one or more than one times. (Admittedly the last of these only happens if > you work at it). > > If it is called then is may be either immediately the last reference to the > object is lost, or it may be later when the garbage collector runs (and not > necessarily the first next time the garbage collector runs). Java finalizers are not called upon VM exit, only when object is swept by GC (for example when the object is destroyed upon program exit), the CPython docs read that this is the case for Python too. Is this behaviour standard for all VM implementations or is implementation-dependent (CPython, Jython, IronPython)? -- Jarek Zgoda Skype: jzgoda | GTalk: zgoda at jabber.aster.pl | voice: +48228430101 "We read Knuth so you don't have to." (Tim Peters) From bockman at virgilio.it Mon Feb 25 07:26:15 2008 From: bockman at virgilio.it (bockman at virgilio.it) Date: Mon, 25 Feb 2008 04:26:15 -0800 (PST) Subject: Newbie: How can I use a string value for a keyword argument? References: Message-ID: <94d32501-c16c-4609-a834-5ad60afa00f7@s12g2000prg.googlegroups.com> On 25 Feb, 12:42, Doug Morse wrote: > Hi, > > My apologies for troubling for what is probably an easy question... it's just > that can't seem to find an answer to this anywhere (Googling, pydocs, etc.)... > > I have a class method, MyClass.foo(), that takes keyword arguments. ?For > example, I can say: > > x = MyClass() > x.foo(trials=32) > > Works just fine. > > What I need to be able to do is call foo() with a string value specifying the > keyword (or both the keyword and value would be fine), something along the > lines of: > > x = MyClass() > y = 'trials=32' > x.foo(y) ? ? ? ?# doesn't work > > or > > x.MyClass() > y = 'trials' > x.foo(y = 32) ? # does the "wrong" thing > Try this: y='trials' x.foo( **{y:32} ) Ciao ----- FB From bbxx789_05ss at yahoo.com Thu Feb 28 06:50:56 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Thu, 28 Feb 2008 03:50:56 -0800 (PST) Subject: more pythonic References: Message-ID: <4200e44a-0859-44b2-af04-68e9c9e98da6@s12g2000prg.googlegroups.com> On Feb 28, 4:48?am, 7stud wrote: > > It's my understanding that the way you insert arguments into queries > has to be done in a db specific way. ? > Rather: It's my understanding that the way you insert arguments into queries *should* be done in a db specific way. ? From stefan_ml at behnel.de Sat Feb 2 09:48:28 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 02 Feb 2008 15:48:28 +0100 Subject: REALLY simple xml reader In-Reply-To: <13q8p3nn7pi9hd9@corp.supernews.com> References: <1090e4100801271040n7bc6b452n346adee02abcd91d@mail.gmail.com> <60do34F1q1qmlU1@mid.uni-berlin.de> <60dsbrF1qj28sU1@mid.uni-berlin.de> <87tzkujeq6.fsf@benfinney.id.au> <13q3ri2707niqc6@corp.supernews.com> <87odb1k9ar.fsf@benfinney.id.au> <13q8p3nn7pi9hd9@corp.supernews.com> Message-ID: <47A482BC.2080907@behnel.de> Steven D'Aprano wrote: > On Fri, 01 Feb 2008 07:51:56 +1100, Ben Finney wrote: > >> Steven D'Aprano writes: >> >>> On Fri, 01 Feb 2008 00:40:01 +1100, Ben Finney wrote: >>> >>>> Quite apart from a human thinking it's pretty or not pretty, it's >>>> *not valid XML* if the XML declaration isn't immediately at the start >>>> of the document . Many >>>> XML parsers will (correctly) reject such a document. >>> You know, I'd really like to know what the designers were thinking when >>> they made this decision. >> Probably much the same that the designers of the Unix shebang ("#!") or >> countless other "figure out whether the bitstream is a specific type" >> were thinking: > > There's no real comparison with the shebang '#!'. It is important that > the shell can recognise a shebang with a single look-up for speed, and > the shell doesn't have to deal with the complexities of Unicode: if you > write your script in UTF-16, bash will complain that it can't execute the > binary file. The shell cares whether or not the first two bytes are 23 > 21. An XML parser doesn't care about bytes, it cares about tags. Or rather about unicode code points. I actually think that you can compare the two. The shell can read the shebang, recognise it, and continue reading up to the first newline to see what needs to be done. That's one simple stream, no problem. Same for the XML parser. It reads the stream and it will not have to look back, even if the declaration requests a new encoding. Just like the shebang has to be at the beginning, the declaration has to be there, too. All I'm saying is that there is a point where you have to draw the line, and the XML spec says, that the XML declaration must be at the beginning of the document, and that it may be followed by whitespace. I think that's clear and simple. It admit that it's questionable if it should be allowed to omit the declaration, but since there is only one case where you are allowed to do that, I'm somewhat fine with this special case. Stefan From muthusamypearlpost at gmail.com Sat Feb 9 05:21:06 2008 From: muthusamypearlpost at gmail.com (sam) Date: Sat, 9 Feb 2008 02:21:06 -0800 (PST) Subject: online marketing make money Message-ID: <36469d35-884e-487b-a2fa-dd679629cd19@s8g2000prg.googlegroups.com> It is new one online business you can earn minimum 1000$ per month great oppertunity to students,house wives,retired persons andall others . http://onlinemarketingmakemoney.blogspot.com From davidson.kris at gmail.com Wed Feb 27 22:39:24 2008 From: davidson.kris at gmail.com (Kris Davidson) Date: Thu, 28 Feb 2008 03:39:24 +0000 Subject: Python IRC Zork Message-ID: Hi, If this has been done before in another language could someone please tell me, if not I was wondering is its possible and what the easier way is to create an IRC bot that allows you to play Zork: I was thinking of just creating a simple Python IRC bot or finding an existing one then have it run Zork and read/write from stdout/stdin. Is that possible? Is there a better or easier way to do it? Are there any existing programs that do something similar? Or just really anything else people have to say on the subject. Thanks Kris From larry.bates at websafe.com Mon Feb 4 10:29:44 2008 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 04 Feb 2008 09:29:44 -0600 Subject: Too many open files In-Reply-To: <47a70bd0$0$3908$426a74cc@news.free.fr> References: <47a70bd0$0$3908$426a74cc@news.free.fr> Message-ID: <1radnXQzePvtsjranZ2dnUVZ_oTinZ2d@comcast.com> AMD wrote: > Hello, > > I need to split a very big file (10 gigabytes) into several thousand > smaller files according to a hash algorithm, I do this one line at a > time. The problem I have is that opening a file using append, writing > the line and closing the file is very time consuming. I'd rather have > the files all open for the duration, do all writes and then close them > all at the end. > The problem I have under windows is that as soon as I get to 500 files I > get the Too many open files message. I tried the same thing in Delphi > and I can get to 3000 files. How can I increase the number of open files > in Python? > > Thanks in advance for any answers! > > Andre M. Descombes Not quite sure what you mean by "a hash algorithm" but if you sort the file (with external sort program) on what you want to split on, then you only have to have 1 file at a time open. -Larry From MartinRinehart at gmail.com Thu Feb 28 09:33:33 2008 From: MartinRinehart at gmail.com (MartinRinehart at gmail.com) Date: Thu, 28 Feb 2008 06:33:33 -0800 (PST) Subject: Python's BNF References: <85ae78f6-056b-4219-9952-66750e3ebf58@e60g2000hsh.googlegroups.com> Message-ID: Implemented all your suggestions, with two exceptions. Changed file read to readlines(), but not open(...).readlines(). I love to say file.close(). Gives me a feeling of security. (We could discuss RAM waste v. I/O speed but this input file is just 10KB, so neither matters.) Removed one of the three globals, but left the other two. Couldn't see any real advantage to passing poor 'ofile' from hand to hand (writeHTML() to writeBody() to writeEntries() ...) as opposed to letting him rest easy in his chair, doing a little writing when called. Also changed the opening doc comment to give you appropriate credit. Thanks again. From andreas.profous at googlemail.com Fri Feb 8 09:10:14 2008 From: andreas.profous at googlemail.com (andreas.profous at googlemail.com) Date: Fri, 8 Feb 2008 06:10:14 -0800 (PST) Subject: Time conversion between UTC and local time Message-ID: <486ff322-dcb5-4903-a86d-178b8a4d5ce2@e10g2000prf.googlegroups.com> Hi all, I have the following problem: There are strings describing a UTC time, e.g. " 2008-01-15 22:32:30" and a string reflecting the time zone e.g. "-05:00". What is an elegant way of getting the local time (considering DST - daylight saving time) with that data? The date is not important, just the local time. The format is not important, the easiest would probably be a tuple (h,m,s) . Thanks in advance From nagle at animats.com Mon Feb 4 14:30:41 2008 From: nagle at animats.com (John Nagle) Date: Mon, 04 Feb 2008 11:30:41 -0800 Subject: Very weird behavior in MySQLdb "execute" Message-ID: <47a76661$0$36336$742ec2ed@news.sonic.net> This has me completely mystified. Some SELECT operations performed through MySQLdb produce different results than with the MySQL graphical client. This failed on a Linux server running Python 2.5, and I can reproduce it on a Windows client running Python 2.4. Both are running MySQL 2.5. The table involved is: CREATE TABLE domaincache ( domain VARCHAR(255) NOT NULL UNIQUE PRIMARY KEY, rating CHAR(1) NULL, rating_info ENUM ('error','no_domain','no_website','blocked','no_location','negative_info','non_commercial','unverified') NULL, special_case ENUM('normal','special'), rating_id BIGINT UNSIGNED NULL, last_update_end TIMESTAMP NOT NULL, version SMALLINT UNSIGNED NOT NULL, INDEX (rating_id) ); Nothing exciting there. In the MySQL query browser, I can do either select * from domaincache where domain = "adwords.google.com" or select * from domaincache where domain = "google.com" and I get one record back from each, with the correct info. That's correct. Querying the database from Python gives different results. The database connection is made with: db = MySQLdb.connect(host="localhost", use_unicode = True, charset = "utf8", user=username, passwd=password, db=database) When I make the same queries from Python, via IDLE, typing in commands: cursor.execute('SELECT * FROM domaincache WHERE domain="adwords.google.com"') returns 0L, no rows, which is wrong. That domain is in the database, and a SELECT from the graphical client will find it. But cursor.execute('SELECT * FROM domaincache WHERE domain="google.com"') returns 1L, one row, which is correct. The database is InnoDB, and CHECK TABLE says the database is valid. Restarting the MySQL instance changes the database. The entry "google.com" disappears, and is replaced by "www.google.com". This must indicate a hanging transaction that wasn't committed. But that transaction didn't come from the Python IDLE session I've been making test calls from. Those queries should match the graphical client exactly. So why don't they agree? From ivan.illarionov at gmail.com Wed Feb 20 00:50:33 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Tue, 19 Feb 2008 21:50:33 -0800 (PST) Subject: Double underscores -- ugly? References: Message-ID: <360395fe-dd12-45eb-a40b-99c7a9e89dcf@v3g2000hsc.googlegroups.com> I would like to see something like %init or &init to be converted to __init__ behind the scenes. And $something to be converted to self.something. But, unfortunately, most Python people would consider this ugly just because Perl uses too much syntactic sugar and anything Perl-like is considered ugly in Python community. So, unless Perl die, I believe that Python will remain sugar-free. From t at nomail.com Sat Feb 16 15:28:00 2008 From: t at nomail.com (T_T) Date: 16 Feb 2008 20:28:00 GMT Subject: simple python script to zip files References: <47b7032c$0$54085$dbd4b001@news.wanadoo.nl> <47b70407$0$54085$dbd4b001@news.wanadoo.nl> <47b73aa3$0$54085$dbd4b001@news.wanadoo.nl> Message-ID: <47b74750$0$54085$dbd4b001@news.wanadoo.nl> > f = zipfile.ZipFile(zipfilename, 'w', > compression=zipfile.ZIP_DEFLATED) > > -tkc Adding the compression rule works great, thanks again! From ndbecker2 at gmail.com Sat Feb 9 17:03:53 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Sat, 09 Feb 2008 17:03:53 -0500 Subject: Turn off ZeroDivisionError? Message-ID: I'd like to turn off ZeroDivisionError. I'd like 0./0. to just give NaN, and when output, just print 'NaN'. I notice fpconst has the required constants. I don't want to significantly slow floating point math, so I don't want to just trap the exception. If I use C code to turn off the hardware signal, will that stop python from detecting the exception, or is python checking for 0 denominator on it's own (hope not, that would waste cycles). From spamspam at spam.eggs Tue Feb 12 17:17:05 2008 From: spamspam at spam.eggs (Ben C) Date: Tue, 12 Feb 2008 16:17:05 -0600 Subject: Recursive generator References: <7x63wt5310.fsf@ruckus.brouhaha.com> Message-ID: On 2008-02-12, Paul Rubin <> wrote: > Paul Hankin writes: >> def genDescendants(self): >> return chain([self], *[child.genDescendants() >> for child in self.children]) > > That is scary. It generates an in-memory list the size of the > whole subtree, at every level. Total memory consumption is maybe > even quadratic, depending on the tree shape, but even if it's > only linear, it's way ugly. This would probably be better (in terms of memory if not beauty): def genDescendants(self): return chain([self], *(child.genDescendants() for child in self.children)) From noname9968 at gmail.com Sat Feb 9 07:18:17 2008 From: noname9968 at gmail.com (Alex) Date: Sat, 09 Feb 2008 15:18:17 +0300 Subject: Edit Python code programmatically In-Reply-To: <13qr5h970g2mrba@corp.supernews.com> References: <13qr5h970g2mrba@corp.supernews.com> Message-ID: <47AD9A09.3060603@gmail.com> Steven D'Aprano wrote: > On Sat, 09 Feb 2008 14:38:29 +0300, Alex wrote: > > >> Which library could you recommend to perform simple editing of Python >> code (from Python program)? >> > > I'm not even sure such a library exists. > Yes they exist, that field is called "code-generation", "generative programming" etc. > > >> For example, open *.py file, find specific >> function definition, add another function call inside, find existing >> call and change parameter value, etc. >> > > Why do you want to do that? I'm not sure what you're trying to > accomplish. Code refactoring? I imagine that's probably best done with > your text editor: at best, your editor will have dedicated refactoring > tools, and at worst, it will have global search and replace. I don't feel like describing all ideas - it's nothing really intersting anyway, just a learning project (to get to know language features), but obviously it's not for regular programming - I know text editors can do that just fine. Simply in some situation I think instead of generating data I'd better generate some code. From wolf_tracks at invalid.com Tue Feb 12 00:37:11 2008 From: wolf_tracks at invalid.com (W. Watson) Date: Mon, 11 Feb 2008 21:37:11 -0800 Subject: Is there a web visitor counter available in Python ... In-Reply-To: References: Message-ID: <6easj.124$tW.106@nlpi070.nbdc.sbc.com> PHP. Well, that's a new one on me. Google gave me some idea of what it's about, and I found some code on how to do it. It requires yet another "programming language", which means finding the editor, etc. Jon "Fluffy" Saul wrote: > On Feb 11, 2008 9:21 PM, W. Watson wrote: >> ... that is free for use without advertising that I can use on my web pages? >> I have no idea is suitable for this. My knowledge of Python is somewhat >> minimal at this point. Maybe Java is better choice. >> >> -- >> Wayne Watson (Nevada City, CA) >> >> Web Page: >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > PHP would be the best choice. > Simple and advanced PHP hit counters can be found with a search of Google. > "PHP hit counter", etc. > -- Wayne Watson (Nevada City, CA) Web Page: From jeff at schwabcenter.com Sat Feb 9 16:29:13 2008 From: jeff at schwabcenter.com (Jeff Schwab) Date: Sat, 09 Feb 2008 13:29:13 -0800 Subject: sort functions in python In-Reply-To: <13qqnga820l8991@corp.supernews.com> References: <13qq49c705dnc2a@corp.supernews.com> <13qqnga820l8991@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > On Fri, 08 Feb 2008 19:09:06 -0800, Jeff Schwab wrote: > >> Steven D'Aprano wrote: >>> On Fri, 08 Feb 2008 17:00:27 -0800, t3chn0n3rd wrote: >>> >>>> Do you think it is relatively easy to write sort algorithms such as >>>> the common Bubble sort in Python as compared to other high level >>>> programming langauges >>> >>> You realise that bubble sort is one of the worst possible sort >>> algorithms possible, particularly on modern hardware? It's not the >>> worst: bogo sort and bozo sort are worse, but bubble sort is still >>> pretty atrocious. >> That's the conventional wisdom, mostly because CS professors need a "bad >> algorithm" to show undergrads, but it's not really accurate. The truth >> is that bubble-sort's performance depends strongly on the input data. In >> the worst case, yes, bubble-sort is O(n^2); however, for almost-sorted >> data (only a few elements out of place), bubble-sort is actually one of >> the fastest known algorithms. > > It depends on what you mean by "bubble sort". There are many different > variations of bubble sort, that are sometimes described by names such as > comb sort, cocktail sort, exchange sort, and sometimes merely referred to > bubble sort. It's rather like any divide-and-conquer sorting algorithm > being called quicksort. > > I'm as guilty of that as anyone else -- the example code I posted, raided > from Wikibooks is very different from this bubble sort algorithm from > PlanetMath: > > http://planetmath.org/encyclopedia/Bubblesort.html > > def bubblesort(L): > done = False > while not done: > done = True > for i in xrange(len(L)-1): > if L[i+1] <= L[i]: > L[i], L[i+1] = L[i+1], L[i] > done = False > return L > > This one runs significantly faster than the earlier one I posted. > > Another vital factor is, what language are you implementing the sort > routine in? The conventional wisdom for low-level languages like assembly > and C doesn't necessarily hold for high-level languages like Python. > Comparisons are slow in Python and fast in C; in C a good algorithm will > minimize the amount of moves, while in Python a good algorithm will > minimize the number of comparisons. > > Finally, what hardware are you running on? There are interactions between > hardware caches and pipes that can ruin the performance of an otherwise > promising algorithm. > > > But all those factors aside, I fear that your attempt to rehabilitate the > reputation of bubble sort is misplaced. Here's another person who wants > to defend bubble sort: > > "A fair number of algorithm purists (which means they've probably never > written software for a living) claim that the bubble sort should never be > used for any reason. Realistically, there isn't a noticeable performance > difference between the various sorts for 100 items or less, and the > simplicity of the bubble sort makes it attractive." > > http://linux.wku.edu/~lamonml/algor/sort/bubble.html > > But then on the same person's page on insertion sort: > > "The insertion sort is a good middle-of-the-road choice for sorting lists > of a few thousand items or less. The algorithm is significantly simpler > than the shell sort, with only a small trade-off in efficiency. At the > same time, the insertion sort is over twice as fast as the bubble sort > and almost 40% faster than the selection sort." > > http://linux.wku.edu/~lamonml/algor/sort/insertion.html > > He gives sample C code for both, and the bubble sort has eight lines of > code, versus nine for insertion sort (excluding bare braces). > > Perhaps what he should have said is: > > "Bubble sort is a tiny bit simpler than insertion sort, and almost twice > as slow!" So basically, you and I agree that the right sorting algorithm for the job depends on the job. I have no particular interest in evangelizing for bubble-sort; however, I hate to see an algorithm (or data structure, or language, or programming style) taken out of the running before the race even starts, just because it's out of fashion. From Graham.Dumpleton at gmail.com Tue Feb 19 21:28:05 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Tue, 19 Feb 2008 18:28:05 -0800 (PST) Subject: problem with mod_python References: <20080217042915.GA24617@debian> Message-ID: <3447f312-87cb-4060-8bd6-78b7b5d1ea09@c33g2000hsd.googlegroups.com> On Feb 20, 6:04 am, Joshua Kugler wrote: > Pradnyesh Sawant wrote: > > Hello, > > I have a small program which does 'import hashlib'. This program runs fine > > with python2.5. But when I try running the same program through > > mod_python, I get the error: 'ImportError: No module named hashlib' in the > > apache2 error.log > > > Searching online suggested me to include md5.so or md5module.so in > > apache2. but I don't see that in a package for debian lenny (the system > > I'm using). > > > So, my Q is, is it possible to make mod_python use the same PYTHONPATH as > > the python2.5 interpreter? if so, how? > > It sounds like your mod_python may be compiled against a different version > of Python than your main installation? How did you install mod_python? How > did you install your main python installation? > > What is the output of the command: > > ldd /path/to/mod_python.so > > (the full path on my system is /usr/lib/apache2/mod_python.so) > > There should be a line something like: > > libpython2.5.so.1.0 => /usr/lib/libpython2.5.so.1.0 (0xb7e37000) > > If it is pointing to libpython.2.4.so.1.0, then that could be the reason for > you troubles. The ldd trick only works if the Python version being used actually supplied a shared library and mod_python was able to link against it, otherwise a static version of Python is embedded in mod_python. Some Linux distributions still possibly don't provide a shared library for Python, or don't correctly symlink the .so into the Python config directory along side the .a so that linkers will find it correctly when -L for config directory is used. This has in part been the fault of Python itself as build from source doesn't necessarily do that symlink. Not sure if this has changed in more recent Python versions. Graham From tim.arnold at sas.com Fri Feb 1 14:47:24 2008 From: tim.arnold at sas.com (Tim Arnold) Date: Fri, 1 Feb 2008 14:47:24 -0500 Subject: build tool opinions Message-ID: Hi, I'm going through the various build tools (i.e., make-like) available and could use some advice. My documentation-build system is written in python and uses the pdflatex and plasTeX engines to create pdfs, html, and docbook XML from latex source files. All that is ok, but I can clean up a lot of code by letting a build tool take care of installing the doc, creating build dirs, interacting with the CMS, etc. So I started out looking at ant, since it's so popular. That led me on to look at SCons since it's written in python, and that led me on to look at 'A-A-P'. Well, there's a lot of options out there. So my question is what should I use? Impossible to answer I know, but it looks like SCons and A-A-P haven't had a lot of development activity--that seems to be because they're stable, not because they've been abandoned. Right now I like the fact that SCons and A-A-P are both written in Python; On the other hand I think I could use Jython and Ant too. Any ideas/opinions/advice would be helpful. --Tim From gagsl-py2 at yahoo.com.ar Thu Feb 28 22:43:37 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 29 Feb 2008 01:43:37 -0200 Subject: (Newbie) Help with sockets. References: <146eb331-a79a-4ac7-ba29-a9935643b20f@d4g2000prg.googlegroups.com> Message-ID: En Fri, 29 Feb 2008 00:20:26 -0200, escribi?: > Hi everyone. I'm fairly new to Python, and even more new to socket > programming. I think I've wrapped my head around sockets, and with > that I want to create a Telnet-based chat server, the idea being > people connect to the telnet servers with their clients and they all > communicate. I've got the code working, but the server sends each > letter to the clients on a new line! I've read about this kind of > thing on Windows on Google, but I can't find a solution to this issue. The telnet client can use "line mode" or "character mode". In "line mode" nothing is sent until the user press Enter; line editing is made on the client side. In "character mode" keystrokes are sent as soon as typed; probably your telnet client is using this mode. -- Gabriel Genellina From j.foster.davis at gmail.com Sat Feb 23 00:03:02 2008 From: j.foster.davis at gmail.com (Jacob Davis) Date: Fri, 22 Feb 2008 21:03:02 -0800 Subject: wxPython Plot always comes to focus on redraw In-Reply-To: References: <34F026F4-EF92-4016-A10F-5BE8752B5D80@gmail.com> Message-ID: <1AA4A6FC-7F77-4E94-A018-C2F3BAC0EA28@gmail.com> Thanks for the reply. This is something that I tried. The documentation for SetFocus() says that it is for keyboard input and that Show() is supposed to show the window. I guess I was misusing the terminology. I tried your suggestion with SetFocus(), Show() and Raise(), with no joy. I think I will try the wxPython list. Thanks Jake On Feb 21, 2008, at 4:36 AM, Steve Holden wrote: > Jacob Davis wrote: >> Hi. >> >> I am using wxPython, and I have a frame that has a notebook in it. >> there are 3 pages in the notebook, 2 of which are Panels and 1 of >> which is a PlotCanvas. The data for the plot changes when I press a >> button that is in the frame, but not in the notebook (as designed). >> the button also makes the plot draw again, since the data has >> changed. >> >> The problem is that whenever I press my button, the focus of the >> notebook "view area" (as opposed to the tabs) changes focus to the >> plot. if I have multiple plots, the focus goes to that plot which >> was >> drawn last in the code. however, if I click anywhere on the panel, >> the >> page of the notebook that is supposed to be in focus is now shown in >> the "view area" of the notebook. >> >> will try to make a sample .py if anybody needs a visual, let me know >> pls. >> >> Thanks for any help! >> >> Jake > > All wxWindow objects have a SetFocus() method. I am unsure why the > system should be changing the focus (it's almost certainly something > you > are asking it to do without realizing), but the easiest way to proceed > if you can't stop the focus from changing (i.e. remove the problem) is > to call SetFocus() on the widget that you want to have the focus after > you've finished (i.e. cure the symptom). > > Or perhaps it's just that I haven't understood the problem correctly. > You probably didn't post the code because it's large (which is good). > The correct action is to pare the program down to the smallest one you > can make that demonstrates the problem, then post that. often during > this process it becomes clear what the problem is! > > It may be that your widget relationships aren't as clean as they might > be: did you produce your layout with an automated tool like wxDesigner > or BoaConstrictor, or did you hack it together by hand? > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC http://www.holdenweb.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list From http Sun Feb 24 21:27:46 2008 From: http (Paul Rubin) Date: 24 Feb 2008 18:27:46 -0800 Subject: Create multiple directories References: <5b42e76f-4b9c-4bdb-93dd-915b1bb26357@z17g2000hsg.googlegroups.com> <7xablpaihu.fsf@ruckus.brouhaha.com> Message-ID: <7x8x19g47x.fsf@ruckus.brouhaha.com> Paul Rubin writes: > fmt = "new_dir%0%d" % len(str(num)) Typo, that was supposed to say "new_dir%%0%d" ... From martin-schmitz at web.de Wed Feb 27 07:48:25 2008 From: martin-schmitz at web.de (Martin Schmitz) Date: Wed, 27 Feb 2008 13:48:25 +0100 Subject: Portable linux python install References: Message-ID: <20080227134825.379afb0e@schmitz-it-consulting.de> Am 26.02.08 schrieb "Mike M" : > I have a python application which I'd like to distribute to thousands > of machines in our server farm. Install everything you need on the oldest box available and package it with PyInstaller (http://pyinstaller.python-hosting.com/). Then you get binaries which are only linked against libc - and as it happens to be the oldest version of libc around you shouldn't have problems running the binaries with newer ones. HTH, Martin From yozara at terra.es Mon Feb 11 02:18:11 2008 From: yozara at terra.es (Zara) Date: Mon, 11 Feb 2008 08:18:11 +0100 Subject: Error on Python References: <2713302a-dade-4c5d-9eba-eb73f4f03d6f@s12g2000prg.googlegroups.com> Message-ID: On Sat, 9 Feb 2008 10:26:26 -0800 (PST), maehhheeyy wrote: >Hi, right now I'm using Python and Multicast. I have the code for >Multicast receiver on Python but I keep getting this error; > >File "", line 1, in bind >error: (10049, "Can't assign requested address") > >The error is coming from this line; >sock.bind ((MCAST_ADDR, MCAST_PORT)) > >Can anyone please help me solve this problem? This error typically arises when the address is neither the IP address of a network connection or 0.0.0.0. If you are trying to connect an IGMP socket under Windows, it may not be treated as a normal socket. You must use the corresponding setsockopt() options, and I am not sure if they are available throguh Python! Search MSDN for IGMP, or lok directly at: http://msdn2.microsoft.com/en-us/library/ms739172(VS.85).aspx If you are trying on *NIX SO, I don't know if this is applicable best regrads, Zara From steve at REMOVE-THIS-cybersource.com.au Thu Feb 7 16:25:34 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 07 Feb 2008 21:25:34 -0000 Subject: OT: Star Wars and parsecs [was Re: Why not a Python compiler?] References: <28eead2f-a40c-414b-bd3d-a941f8a851a2@d70g2000hsb.googlegroups.com> <7da40f42-f64f-4939-a0dc-d24d1ff85f2d@v4g2000hsf.googlegroups.com> <13qjktdbe76da00@corp.supernews.com> <13qmp56btnr55a4@corp.supernews.com> Message-ID: <13qmtqebm4t6979@corp.supernews.com> On Thu, 07 Feb 2008 13:44:05 -0700, Ivan Van Laningham wrote: > Gary Kurtz at SunCon 77 explained that it was a test to see if Obi-Wan > knew what he was doing; supposedly, Obi-Wan's expression indicated that > he knew Solo was feeding him shit. Why the hell would the pilot care whether the passengers knew what a parsec was? Did Concorde pilots quiz their passengers what Mach 1 means? Especially a pirate like Solo, who really only cared about one question: "can the passenger pay?". > I think Lucas didn't have a clue, myself; it's not credible that > citizens of a starfaring civilization who deliberately set out to hire a > starship wouldn't know the difference between time and distance. Occam's > razor says Lucas screwed up and doesn't want to admit it. For sure. -- Steven From ptmcg at austin.rr.com Sat Feb 16 23:06:52 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 16 Feb 2008 20:06:52 -0800 (PST) Subject: Help Parsing an HTML File References: <15f9198f-fa2a-4f4f-8f87-7402b03743e1@s13g2000prd.googlegroups.com> Message-ID: <94b9e658-eaa6-43d3-8ffe-65b49ebe3749@o10g2000hsf.googlegroups.com> On Feb 15, 3:28?pm, egonslo... at gmail.com wrote: > Hello Python Community, > > It'd be great if someone could provide guidance or sample code for > accomplishing the following: > > I have a single unicode file that has ?descriptions of hundreds of > objects. The file fairly resembles HTML-EXAMPLE pasted below. > Pyparsing was mentioned earlier, here is a sample with some annotating comments. I'm a little worried when you say the file "fairly resembles HTML- EXAMPLE." With parsers, the devil is in the details, and if you have scrambled this format - the HTML attributes are especially suspicious - then the parser will need to be cleaned up to match the real input. If the file being parsed really has proper HTML attributes (of the form ), then you could simplify the code to use the pyparsing method makeHTMLTags. But the example I wrote matches the example you posted. -- Paul # encoding=utf-8 from pyparsing import * data = """

Ros?H1-1

Ros?H2-1

... snip ... """ # define and tags CL = CaselessLiteral h1,h2,cmnt,br = \ map(Suppress, map(CL,["<%s>" % s for s in "h1 h2 comment br".split()])) h1end,h2end,cmntEnd,divEnd = \ map(Suppress, map(CL,["" % s for s in "h1 h2 comment div".split()])) # h1,h1end = makeHTMLTags("h1") # define special format for
, incl. optional quoted string "attribute" div = "<" + CL("div") + Optional(QuotedString('"'))("name") + ">" div.setParseAction( lambda toks: "name" in toks and toks.name.title() or "DIV") # define body entries h1Entry = h1 + SkipTo(h1end) + h1end h2Entry = h2 + SkipTo(h2end) + h2end comment = cmnt + SkipTo(cmntEnd) + cmntEnd divEntry = div + SkipTo(divEnd) + divEnd # just return nested tokens grammar = (OneOrMore(Group(h1Entry + (Group(h2Entry + (OneOrMore(Group(divEntry)))))))) grammar.ignore(br) grammar.ignore(comment) results = grammar.parseString(data) from pprint import pprint pprint(results.asList()) print # return nested tokens, with dict grammar = Dict(OneOrMore(Group( h1Entry + Dict(Group(h2Entry + Dict(OneOrMore(Group(divEntry)))))))) grammar.ignore(br) grammar.ignore(comment) results = grammar.parseString(data) print results.dump() Prints: [['Ros\xe9H1-1', ['Ros\xe9H2-1', ['DIV', 'Ros\xe9DIV-1'], ['Segment1', 'Ros\xe9SegmentDIV1-1'], ['Segment2', 'Ros\xe9SegmentDIV2-1'], ['Segment3', 'Ros\xe9SegmentDIV3-1']]], ['PinkH1-2', ['PinkH2-2', ['DIV', 'PinkDIV2-2'], ['Segment1', 'PinkSegmentDIV1-2']]], ['BlackH1-3', ['BlackH2-3', ['DIV', 'BlackDIV2-3'], ['Segment1', 'BlackSegmentDIV1-3']]], ['YellowH1-4', ['YellowH2-4', ['DIV', 'YellowDIV2-4'], ['Segment1', 'YellowSegmentDIV1-4'], ['Segment2', 'YellowSegmentDIV2-4']]]] [['Ros\xe9H1-1', ['Ros\xe9H2-1', ['DIV', 'Ros\xe9DIV-1'], ['Segment1', 'Ros\xe9SegmentDIV1-1'], ['Segment2', 'Ros\xe9SegmentDIV2-1'], ['Segment3', 'Ros\xe9SegmentDIV3-1']]], ['PinkH1-2', ['PinkH2-2', ['DIV', 'PinkDIV2-2'], ['Segment1', 'PinkSegmentDIV1-2']]], ['BlackH1-3', ['BlackH2-3', ['DIV', 'BlackDIV2-3'], ['Segment1', 'BlackSegmentDIV1-3']]], ['YellowH1-4', ['YellowH2-4', ['DIV', 'YellowDIV2-4'], ['Segment1', 'YellowSegmentDIV1-4'], ['Segment2', 'YellowSegmentDIV2-4']]]] - BlackH1-3: [['BlackH2-3', ['DIV', 'BlackDIV2-3'], ['Segment1', 'BlackSegmentDIV1-3']]] - BlackH2-3: [['DIV', 'BlackDIV2-3'], ['Segment1', 'BlackSegmentDIV1-3']] - DIV: BlackDIV2-3 - Segment1: BlackSegmentDIV1-3 - PinkH1-2: [['PinkH2-2', ['DIV', 'PinkDIV2-2'], ['Segment1', 'PinkSegmentDIV1-2']]] - PinkH2-2: [['DIV', 'PinkDIV2-2'], ['Segment1', 'PinkSegmentDIV1-2']] - DIV: PinkDIV2-2 - Segment1: PinkSegmentDIV1-2 - Ros?H1-1: [['Ros\xe9H2-1', ['DIV', 'Ros\xe9DIV-1'], ['Segment1', 'Ros \xe9SegmentDIV1-1'], ['Segment2', 'Ros\xe9SegmentDIV2-1'], ['Segment3', 'Ros\xe9SegmentDIV3-1']]] - Ros?H2-1: [['DIV', 'Ros\xe9DIV-1'], ['Segment1', 'Ros \xe9SegmentDIV1-1'], ['Segment2', 'Ros\xe9SegmentDIV2-1'], ['Segment3', 'Ros\xe9SegmentDIV3-1']] - DIV: Ros?DIV-1 - Segment1: Ros?SegmentDIV1-1 - Segment2: Ros?SegmentDIV2-1 - Segment3: Ros?SegmentDIV3-1 - YellowH1-4: [['YellowH2-4', ['DIV', 'YellowDIV2-4'], ['Segment1', 'YellowSegmentDIV1-4'], ['Segment2', 'YellowSegmentDIV2-4']]] - YellowH2-4: [['DIV', 'YellowDIV2-4'], ['Segment1', 'YellowSegmentDIV1-4'], ['Segment2', 'YellowSegmentDIV2-4']] - DIV: YellowDIV2-4 - Segment1: YellowSegmentDIV1-4 - Segment2: YellowSegmentDIV2-4 From luismgz at gmail.com Sun Feb 24 00:06:08 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M._Gonz=E1lez?=) Date: Sat, 23 Feb 2008 21:06:08 -0800 (PST) Subject: Seeing "locals()" from imported function Message-ID: <9fbdbc65-1c3e-4591-8113-d0cba502c08f@p73g2000hsd.googlegroups.com> I apologize for this very basic question, but I can't understand how this works... I want to import a function from module B into my main script A, so this function can see and use the locals from A. For example: def auto(): urls = ['/', 'index'] for k,v in __main__.locals().items(): # these "locals" are the ones of the main script if isinstance(v,type) and k != 'index': urls.append('/%s' %k) urls.append(k) return tuple(urls) Of course this doesn't work... Any hint? Luis From paddy3118 at googlemail.com Sat Feb 9 01:13:05 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 8 Feb 2008 22:13:05 -0800 (PST) Subject: sort functions in python References: Message-ID: <70e4bf36-f8d6-46b8-92f1-a4a9eb050432@i7g2000prf.googlegroups.com> On 9 Feb, 01:00, t3chn0n3rd wrote: > Do you think it is relatively easy to write sort algorithms such as > the common Bubble sort in Python as compared to other high level > programming langauges Hi, >From a quick google, you could compare the sources here: http://www.daniweb.com/code/snippet452.html with those from here: http://cg.scs.carleton.ca/~morin/misc/sortalg/ (It seems that sort routines are a favourite for showing off Java applet capability). - Paddy. P.S. I also found this absolute gem: The intelligent design sort, "works outside of time .." http://www.dangermouse.net/esoteric/intelligentdesignsort.html :-) From spgarg04 at gmail.com Sun Feb 17 11:09:54 2008 From: spgarg04 at gmail.com (Surya Prakash Garg) Date: Sun, 17 Feb 2008 21:39:54 +0530 Subject: Animated GIF in Tkinter Message-ID: <5a22a1610802170809u67f691a3w9072d255037513e9@mail.gmail.com> Hello, I have created a frame in which i want to display an animated progressbar in a canvas. I use PhotoImage function of PIL. But it doesn't display the animated gif code looks like this self.imgobj = PhotoImage(file=imgpath) self.c = Canvas(self.frame2, bg='white',width=64,height=310) self.c.place(x=x0,y=y0) self.c.create_image(x0,y0,image=self.imgobj,anchor=NW) did a lot of googling on it. but nothing found. I can't switch to wxPython. Please help me. thanks -- Surya Prakash Garg Bangalore +919886801350 -------------- next part -------------- An HTML attachment was scrubbed... URL: From j.foster.davis at gmail.com Sat Feb 23 00:01:10 2008 From: j.foster.davis at gmail.com (Jacob Davis) Date: Fri, 22 Feb 2008 21:01:10 -0800 Subject: wxPython Plot always comes to focus on redraw In-Reply-To: <5c220d1d-f820-4024-976e-1b172f936b08@t66g2000hsf.googlegroups.com> References: <5c220d1d-f820-4024-976e-1b172f936b08@t66g2000hsf.googlegroups.com> Message-ID: Thanks for the reply. The parent is a notebook. (the Plotcanvas is a page in the notebook) I tried to make the page of the notebook a panel, and then make the PlotCanvas a child of this panel, but the Plot would not show up when drawn. I may have time to make a mini program to duplicate the error in the future... On Feb 21, 2008, at 6:14 AM, Mike Driscoll wrote: > On Feb 21, 2:57 am, Jacob Davis wrote: >> Hi. >> >> I am using wxPython, and I have a frame that has a notebook in it. >> there are 3 pages in the notebook, 2 of which are Panels and 1 of >> which is a PlotCanvas. The data for the plot changes when I press a >> button that is in the frame, but not in the notebook (as designed). >> the button also makes the plot draw again, since the data has >> changed. >> >> The problem is that whenever I press my button, the focus of the >> notebook "view area" (as opposed to the tabs) changes focus to the >> plot. if I have multiple plots, the focus goes to that plot which >> was >> drawn last in the code. however, if I click anywhere on the panel, >> the >> page of the notebook that is supposed to be in focus is now shown in >> the "view area" of the notebook. >> >> will try to make a sample .py if anybody needs a visual, let me know >> pls. >> >> Thanks for any help! >> >> Jake > > Just a show in the dark, but is the plotcanvas object's parent a frame > or a panel? If it's the frame, than that's probably what the problem > is. > > You may want to post to the wxPython list where you'll get wx geeks to > answer your question and you can learn a lot from them too. Here's a > link where you can sign up: http://wxpython.org/maillist.php > > Mike > > -- > http://mail.python.org/mailman/listinfo/python-list From dhwild at talktalk.net Tue Feb 19 17:33:48 2008 From: dhwild at talktalk.net (David H Wild) Date: Tue, 19 Feb 2008 22:33:48 +0000 (GMT) Subject: Encrypting a short string? References: <61o2t0F205p5fU1@mid.individual.net> <13rmlec867jcnc2@corp.supernews.com> Message-ID: <47bb5a0c$0$1344$834e42db@reader.greatnowhere.com> In article <13rmlec867jcnc2 at corp.supernews.com>, Steven D'Aprano wrote: > > I really don't recommend the ROT13 cipher, as this is extremely easy to > > crack. Most grade school kids could break this one in seconds. ;-) > I think you missed the point. Any recommendation to use ROT13 is likely > to be a joke. A recommendation to use Triple ROT13 is *absolutely* a > joke. ROT13 does have a legitimate use, but it's not as a cypher. It is really the equivalent of the newspaper quiz where the answers are upside down at the bottom of the page. By doing this you stop seeing the answers too early. -- David Wild using RISC OS on broadband www.davidhwild.me.uk From qwe at ngi.it Sun Feb 10 11:31:59 2008 From: qwe at ngi.it (MASI) Date: Sun, 10 Feb 2008 17:31:59 +0100 Subject: Tkinter equiv for setPalette References: <47aeda20$0$2988$ba620e4c@news.skynet.be> Message-ID: Il Sun, 10 Feb 2008 12:03:59 +0100, Helmut Jarausch ha scritto: > Hi, > > I am to convert an old Perl-Tk script to Python. > It starts by > my $MW= new MainWindow; > $MW->setPalette(background => 'AntiqueWhite1', foreground => 'blue'); > > Is there an equivalent for Tkinter? How can I set default colors for > background and foreground for the whole application (root window and its > children) > > Many thanks for a hint, > Helmut. You have two options: 1) put your preference in a file eg file 'tk_option': *foreground: blue *background: green *Entry*background: red and read it root = Tkinter.Tk() root.option_readfile('tk_option') 2) in your program whit option_add eg root = Tkinter.Tk() root.option_add('*foreground', 'blue') root.option_add('*background', 'green') root.option_add('*Entry*background', 'red') From toddw at activestate.com Thu Feb 7 12:25:44 2008 From: toddw at activestate.com (Todd Whiteman) Date: Thu, 07 Feb 2008 09:25:44 -0800 Subject: Paramiko SFTP autologon using id_dsa.pub In-Reply-To: <5491b0ed-946a-4b5b-8f2a-75e900df0be9@e23g2000prf.googlegroups.com> References: <5491b0ed-946a-4b5b-8f2a-75e900df0be9@e23g2000prf.googlegroups.com> Message-ID: <47AB3F18.3080308@activestate.com> Mike Hjorleifsson wrote: > I wrote a lil module using paramiko's module to send a file via > sftp.. it works great using the username and password. > I would prefer to use id_dsa.pub to have an autologon and not save > the > password anywhere on the disk.. I cant find a good example of this. > Can anyone help ? Hi Mike, If you download the Paramiko zip archive: http://www.lag.net/paramiko/download/paramiko-1.7.2.zip You can find examples of loading and using public/private keys for automated logins in the code under the "demos" sub folder. Cheers, Todd From ggpolo at gmail.com Sun Feb 3 13:55:29 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Sun, 3 Feb 2008 16:55:29 -0200 Subject: Python GUI toolkit In-Reply-To: References: <1s8h75-vbf.ln1@strongwill.g2ctech> Message-ID: 2008/2/3, Christian Heimes : > Jorge Godoy wrote: > > Qt is a the best choice, IMHO. Nice support, free if you write free > > software, very nice API, nice tools to develop with and the best looking > > widget system for *nix and mobile phones. > > > PyQt4 forces you to either release your software under GPL or buy a > license. Qt3 and Qt4 allow many more open source licenses but PyQt's > license module doesn't. > PyQt follows same licensing as Qt, so what licenses does Qt4 supports besides GPL and Qt commercial license ? > > Christian > > > PS: I also prefer Qt4 over wx and GTK. :) > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From steve at holdenweb.com Sun Feb 24 12:46:23 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 24 Feb 2008 12:46:23 -0500 Subject: How about adding rational fraction to Python? In-Reply-To: <97f30679-483d-4751-9a6e-0858b36eb426@d4g2000prg.googlegroups.com> References: <13rde22ktgpu532@corp.supernews.com> <26641b5f-d6cb-45a6-8736-7d130d1a5aee@u10g2000prn.googlegroups.com> <13a4316e-3ce7-4b3e-b418-6efb988a8845@q78g2000hsh.googlegroups.com> <676ca28c-b471-41c8-8661-fcd2ea8c23f0@i12g2000prf.googlegroups.com> <74b95b3b-1d6a-42a6-b55d-e77a868b1ffe@64g2000hsw.googlegroups.com> <70ecaf16-7308-455f-9048-730b2b2f9f2f@p43g2000hsc.googlegroups.com> <13rf9tvbkt66r2a@corp.supernews.com> <198927a7-9478-42b3-a972-82049f0130ac@u10g2000prn.googlegroups.com> <1bc9bba7-dc7f-4cfe-8e1c-fa5901c9f556@n77g2000hse.googlegroups.com> <97f30679-483d-4751-9a6e-0858b36eb426@d4g2000prg.googlegroups.com> Message-ID: Lie wrote: > On Feb 18, 1:25 pm, Carl Banks wrote: >> On Feb 17, 1:45 pm, Lie wrote: >> >>>> Any iteration with repeated divisions and additions can thus run the >>>> denominators up. This sort of calculation is pretty common (examples: >>>> compound interest, numerical integration). >>> Wrong. Addition and subtraction would only grow the denominator up to >>> a certain limit >> I said repeated additions and divisions. > > Repeated Addition and subtraction can't make fractions grow > infinitely, only multiplication and division could. > On what basis is this claim made? (n1/d1) + (n2/d2) = ((n1*d2) + (n2*d1)) / (d1*d2) If d1 and d2 are mutually prime (have no common factors) then it is impossible to reduce the resulting fraction further in the general case (where n1 = n2 = 1, for example). >> Anyways, addition and subtraction can increase the denominator a lot >> if for some reason you are inputing numbers with many different >> denominators. > > Up to a certain limit. After you reached the limit, the fraction would > always be simplifyable. > Where does this magical "limit" appear from? > If the input numerator and denominator have a defined limit, repeated > addition and subtraction to another fraction will also have a defined > limit. Well I suppose is you limit the input denominators to n then you have a guarantee that the output denominators won't exceed n!, but that seems like a pretty poor guarantee to me. Am I wrong here? You seem to be putting out unsupportable assertions. Please justify them or stop making them. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From diljeet_kr at yahoo.com Mon Feb 25 22:40:06 2008 From: diljeet_kr at yahoo.com (diljeet kaur) Date: Mon, 25 Feb 2008 19:40:06 -0800 (PST) Subject: buliding log files Message-ID: <361454.10723.qm@web52802.mail.re2.yahoo.com> hi im working on pyqt environment i want to know how to take log or how to build log files of the output --------------------------------- Looking for last minute shopping deals? Find them fast with Yahoo! Search. -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Fri Feb 22 03:45:59 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 22 Feb 2008 00:45:59 -0800 (PST) Subject: Return value of an assignment statement? References: <6d945394-739e-4c47-ad71-faaab8f9d566@34g2000hsz.googlegroups.com> <5ffc7183-6e32-42d1-b9a1-a7514cd085c3@i7g2000prf.googlegroups.com> Message-ID: On Feb 21, 6:52 pm, Steve Holden wrote: > mrstephengross wrote: > >> What you can't do (that I really miss) is have a tree of assign-and-test > >> expressions: > >> import re > >> pat = re.compile('some pattern') > >> if m = pat.match(some_string): > >> do_something(m) > > > Yep, this is exactly what I am (was) trying to do. Oh well.... Any > > clever ideas on this front? > > The syntax is the way it is precisely to discourage that kind of clever > idea. Don't be ridiculous. Assignment operators are maybe one of the worst things in existence, but this particular use case (running a sequence of tests like the above) is perfectly useful and good. Some Pythonistas will swear to their grave and back that should be done by factoring out the tests into a list and iterating over it, and NO OTHER WAY WHATSOEVER, but I don't buy it. That's a lot of boilerplate--the very thing Python is normally so good at minimizing-- when it might not be needed. It would be the right thing for a complex, pluggable, customizable input filter; but is rarely a better solution for a simple text processing script. Quick, at a glance, which code snippet will you understand faster (pretend you know Perl): if (/name=(.*)/) { $name = chop(\1); } elsif (/id=(.*)/) { $id = chop(\1); } elsif (/phone=(.*)/) { $phone = chop(\1); } vs. def set_phone_number(m): phone = m.group(1).strip() def set_id(m): id = m.group(1).strip() def set_name(m): name = m.group(1).strip() _line_tests = [ (r"phone=(.*)", set_phone_number), (r"name=(.*)", set_name), (r"id=(.*)", set_id), ] for pattern,func in _line_tests: m = re.match(pattern,line) if m: func(m) At this small scale, and probably at much larger scales too, the Perl example blows the Python example out of the water in terms of readability. And that's counting Perl's inherent unreadableness. If it were a priority, Python could support this set-and-test idiom, and without an assignment operator. (Notice Perl doesn't use assignment operator here.) For example, a syntax like this (where the scope of m is local to the if-condition and the body of the if- statement: if m where m = re.match(r"name=(.*)",line): name = m.group(1).strip() elif m where m = re.match(r"id=(.*)",line): id = m.group(1).strip() elif m where m = re.match(r"phone=(.*)",line): phone = m.group(1).strip() This won't happen because the set-and-test idiom is relatively minor and not deemed worthy of syntax support. But if it were there, there'd really be nothing clever about it. Carl Banks From luismgz at gmail.com Fri Feb 15 07:22:37 2008 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M._Gonz=E1lez?=) Date: Fri, 15 Feb 2008 04:22:37 -0800 (PST) Subject: Is there a way to use .NET DLL from Python References: <85706ba0-8c24-4324-9a79-98c97fc802db@e4g2000hsg.googlegroups.com> <6c2845aa-aec5-4b75-852a-551b9cd1d6ab@f10g2000hsf.googlegroups.com> <5845a12f-41dd-4bb3-8684-483e93f55c5f@e25g2000prg.googlegroups.com> <5cbdc3cf-cb84-49e5-b746-2eca0feeb97d@i7g2000prf.googlegroups.com>, <2298129a-3ca5-41f9-86ed-28805397fd54@f47g2000hsd.googlegroups.com> <2a883225-7622-4dc4-be85-daf4ff3cfe6c@u10g2000prn.googlegroups.com> Message-ID: <5f3324a6-3e62-4012-aac3-513169b6e800@e6g2000prf.googlegroups.com> On Feb 14, 6:26 pm, Fuzzyman wrote: > On Feb 13, 6:58 pm, "Luis M. Gonz?lez" wrote: > > > > > On 13 feb, 00:26, Dino Viehland wrote: > > > > >> Oh, I know what you mean. > > > >> But that was exactly the reason for having a .DLLs folder, isn't it? > > > >> When you place an assembly into this folder, you avoid having to write > > > >> this boilerplate code, and simply import the assembly as you would > > > >> with a normal python module. At least, that?s how it worked in > > > >> previous versions... > > > >No. You have always had to add references to assemblies before being > > > >able to use the namespaces they contain. You even have to do this with > > > >C# in Visual Studio. > > > > This *should* work in bothIronPython1.x and IronPyton 2.0 - the catch though is that it's implemented in the default site.py we ship with. So if you do the usual thing and use CPython's Lib directory you'll lose this feature w/o copying it over. > > > Sorry Dino, I don't understand... > > What does Cpython's Lib have to do with it? > > If you have the CPython standard library in your IRONPYTHONPATH, then > when IronPython does it's normal 'import site' on startup the CPython > one will be used instead of the default IronPython one... > > Michael Foordhttp://www.manning.com/foord I see. Thank you! Luis From SaqibQureshi at gmail.com Thu Feb 21 01:47:02 2008 From: SaqibQureshi at gmail.com (Saqib Mehmood) Date: Wed, 20 Feb 2008 22:47:02 -0800 (PST) Subject: ENMAC Mobile Phones, iPods EQ100 www.enmac.com.hk References: <1bd560ad-b579-49e5-abeb-2111d2843aa6@e25g2000prg.googlegroups.com> Message-ID: <0522f5b5-8dad-488d-b6e7-302a63b9d397@e60g2000hsh.googlegroups.com> On Jan 24, 1:43 pm, Farooq wrote: > www.enmac.com.hk > GSM Mobile Phones, Digital iPods, Digital Clocks, Digital Pens, > Digital Quran. Enjoy these products with Islamic Features (Complete > Holy Quran with Text and Audio, Tafaseer books, Ahadees Books, Daily > Supplications, Universal Qibla Direction, Prayer Timing and much more) > visit our website for more information. from where I can get the prices for there products. Regards, Saqib From bots.dce at gmail.com Sat Feb 9 03:33:29 2008 From: bots.dce at gmail.com (bots) Date: Sat, 9 Feb 2008 00:33:29 -0800 (PST) Subject: troika 2008 Message-ID: <4d87fb22-bab7-4911-8807-f684efd62b03@v67g2000hse.googlegroups.com> Hello programmers, IEEE Student branch, Delhi College of Engineering invites you to be a part of its much awaited technical fest TROIKA '08 Get ready to enter the battle where your analytical skills and mental acumen are tested to their maximum, where time runs fast and beating the odds is a dire necessity. Welcome to the BITS, BYTES & BOTS saga, a battlefield where the brainstormers fight to rule the binary world. Code hard and fast and you might be the next king in town. Exciting cash prizes to be won!!! BITS: On-site programming The event is held on a two-tier basis. The Prelims consist of an elimination round from which the top coders will be selected for the final programming challenge. Whilst logic might be the strongest, the time slips away fast. Grab the chance to make it a win of a lifetime. Registration has started for the event. Event date: 19th Feb, 2008 For details see www.troika.dcetech.com Queries & Registration: bits.dce at gmail.com BYTES: Overnight Online Programming Contest The event consists of a single round of programming contest in which the participants code among the toughest of competitors. But if your logic is right, you may outrun the best of the best. Be a part of BYTES and let the race begin. Registrations open. Event date: 16th Feb, 2008 For details see www.troika.dcetech.com Queries & Registration: bytes.dce at gmail.com BOTS: Virtual-Bot Programming Contest Based on the theme of the Pirates of the Caribbean, in this programming contest you develop a code to run a virtual bot. The task is to find a path to move objects to their destinations avoiding all possible obstacles and hindrances. Sure the going is tough and the enemies are strong, but get your moves right and you will be surprised with the rewards that come your way. Problem statement released. Event date: 20th Feb, 2008 For details see www.troika.dcetech.com Queries & Registration: bots.dce at gmail.com From gagsl-py2 at yahoo.com.ar Tue Feb 26 00:01:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 26 Feb 2008 03:01:33 -0200 Subject: Odd behaviour of *.pth files and Apache References: <20080221135525.e4f59094.darcy@druid.net> <20080223095245.7c6af2e1.darcy@druid.net> Message-ID: En Sat, 23 Feb 2008 12:52:45 -0200, D'Arcy J.M. Cain escribi?: > On Thu, 21 Feb 2008 13:55:25 -0500 > "D'Arcy J.M. Cain" wrote: >> I tried searching the archives for information on this but nothing >> seemed to be germane. I am running Python sripts as CGI under Apache >> and I have a .pth file in site-packages that includes directory that >> has another .pth in it. Sometimes it picks up the paths in the >> second .pth and sometimes it does not. It always seems to work if I am >> working in a location not in the ServerRoot but if I use the main site >> it does not pick up the directories in the included .pth. > > I have more information now. It seems that it recurses the .pth files > it finds in PYTHONPATH but not for directories found in the .pth files > in site-packages. Is this expected behaviour? The documentation > suggests that it should pick up both. If a .pth file contains a valid directory, it is added to sys.path but it's not searched for additional .pth files. From http://docs.python.org/lib/module-site.html "A path configuration file is a file whose name has the form package.pth AND EXISTS IN ONE OF THE FOUR DIRECTORIES MENTIONED ABOVE" (emphasis by me) (the four directories being .../lib/python2.5/site-packages, site-python, etc.) (Mmm, what the 2.5 docs say is not exactly the same as the actual code in site.py, and the version in http://docs.python.org/dev/library/site.html is not the same as the svn version of site.py... anyway, directories added by mean of .pth files are not recursively searched for more .pth files) -- Gabriel Genellina From darcy at druid.net Thu Feb 28 11:22:43 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Thu, 28 Feb 2008 11:22:43 -0500 Subject: How about adding rational fraction to Python? In-Reply-To: References: <7xk5kra0p1.fsf@ruckus.brouhaha.com> <7xy797s966.fsf@ruckus.brouhaha.com> <7xskzfrob1.fsf@ruckus.brouhaha.com> <7x63wbez2b.fsf@ruckus.brouhaha.com> <13sc3ccds5ap5a9@corp.supernews.com> <13scs8k1kh9nk81@corp.supernews.com> Message-ID: <20080228112243.bd752e99.darcy@druid.net> On Thu, 28 Feb 2008 06:10:13 -0800 (PST) Carl Banks wrote: > On Feb 28, 3:30 am, Dennis Lee Bieber wrote: > > Automatic conversions, okay... but converting a result when all > > inputs are of one time, NO... > > People, this is so cognitive dissonance it's not even funny. I'll say. > There is absolutely nothing obvious about 1/2 returning a number that > isn't at least approximately equal to one half. There is nothing self- > evident about operations maintaining types. Not obvious to you. You are using subjective perception as if it was a law of nature. If "obvious" was the criteria then I would argue that the only proper result of integer division is (int, int). Give me the result and the remainder and let me figure it out. > You people can't tell the difference between "obvious" and "learned > conventions that came about because in limitations in the hardware at > the time". Nobody would have come up with a silly rule like "x op y > must always have the same type as x and y" if computer hardware had > been up to the task when these languages were created. What makes you say they weren't? Calculating machines that handled floating point are older than Python by far. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From george.sakkis at gmail.com Tue Feb 5 22:26:39 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 5 Feb 2008 19:26:39 -0800 (PST) Subject: What is the most simple, quicket, yet most powerful python Web-Framework? References: <5d022604-289d-4d4c-bd9a-286435cf77a6@d21g2000prf.googlegroups.com> Message-ID: <6695d77a-6b2b-44a0-8250-c7693a66d19c@m34g2000hsb.googlegroups.com> xkenneth wrote: > For the DB backend I'm planning on using ZODB. ZODB is actually > quite amazing, and after using it, I honestly can't think of a > reason for using a SQL database. Well, one reason is that this probably rules out most of your options since most web frameworks include (or integrate with) an ORM layer, which in turn talks to a (relational) database. If you're sold on ZODB, you may want to evaluate Grok [1], a Web framework built on top of Zope 3 that doesn't seem to require knowledge of Zope internals. HTH, George [1] http://grok.zope.org/ From miki.tebeka at gmail.com Thu Feb 21 08:41:58 2008 From: miki.tebeka at gmail.com (Miki) Date: Thu, 21 Feb 2008 05:41:58 -0800 (PST) Subject: Tkinter OSX and "lift" References: <47BD7D5F.1060205@codebykevin.com> Message-ID: <29454149-0dfa-4092-a625-0955dbc6ca5d@e10g2000prf.googlegroups.com> Hello Kevin, > Tk.lift doesn't seem to work on OSX (Python 2.5.1). >> If you click on the PythonLauncher application that runs in your dock >> when this script is executed, the window comes into focus fine. You're right, but I want to window to be initially in focus (without the user clicking on the python launcher icon). All the best, -- Miki http://pythonwise.blogspot.com From PieSquared at gmail.com Sun Feb 17 13:32:40 2008 From: PieSquared at gmail.com (Pie Squared) Date: Sun, 17 Feb 2008 10:32:40 -0800 (PST) Subject: Python Memory Manager Message-ID: I've been looking at the Python source code recently, more specifically trying to figure out how it's garbage collector works. I've gathered that it uses refcounting as well as some cycle-detection algorithms, but I haven't been able to figure out some other things. Does Python actually have a single 'heap' where all the data is stored? Because PyObject_HEAD seemed to imply to me it was just a linked list of objects, although perhaps I didnt understand this correctly. Also, if it does, how does it deal with memory segmentation? This question bothers me because I've been trying to implement a moving garbage collector, and am not sure how to deal with updating all program pointers to objects on the heap, and thought perhaps an answer to this question would give me some ideas. (Also, if you know any resources for things like this, I'd be grateful for links/names) Thanks in advance, Pie Squared From steve at holdenweb.com Thu Feb 21 19:16:15 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 21 Feb 2008 19:16:15 -0500 Subject: Return value of an assignment statement? In-Reply-To: References: <6d945394-739e-4c47-ad71-faaab8f9d566@34g2000hsz.googlegroups.com> <835a4fc1-f62a-4141-bca4-4e4f52519466@s37g2000prg.googlegroups.com> <5sudnTSXrZY0aCDanZ2dnUVZ_rKtnZ2d@comcast.com> <67ff8198-1d7d-4690-a9b6-42ebab2e642f@p73g2000hsd.googlegroups.com> Message-ID: Jeff Schwab wrote: > bruno.desthuilliers at gmail.com wrote: [...] >> Now there's no reason to feel nervous about this. All you have to >> remember is that Python never copy anything unless explicitely asked >> for. > > It's not that simple. After a statement like: > > a = b > > Whether a and b denote the same object depends on what kind of object b > represented in the first place. Surely this is exactly wrong. Is there a single example you can think of where a = b assert a is b, "Oops!" would raise and exception? Perhaps you meant to use an augmented assignment operation? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From rw at smsnet.pl Fri Feb 22 13:12:09 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Fri, 22 Feb 2008 19:12:09 +0100 Subject: Tkinter Menu Item Activation References: <71e3a86d-f344-4819-8db9-28710d0fdaf4@z17g2000hsg.googlegroups.com> Message-ID: <87tzk0rhc6.fsf@merkury.smsnet.pl> MartinRinehart at gmail.com writes: > Tkinter definitely deserves more respect! I'm making rapid progress > and it looks good. > > But am stuck on this: I want the File/Save state to change from > disabled to enabled, depending on whether or not there is something to > save (Text modified). Google returns results in every language except > Python. > Sub problems: how to change state of menu item? how to detect changes > in Text widget? > > Help appreciated. State of menu items can be changed like this: import Tkinter as Tk def hello(): if mfile.entrycget(2, 'state') == 'disabled': state = 'normal' else: state = 'disabled' mfile.entryconfigure(2, state=state) root = Tk.Tk() menubar = Tk.Menu(root) mfile = Tk.Menu(menubar) mfile.add_command(label="Open", command=hello) mfile.add_command(label="Save", command=hello) menubar.add_cascade(label='File', menu=mfile) root.config(menu=menubar) root.mainloop() But I think that you should read this: http://effbot.org/zone/vroom.htm HTH, Rob From stefan_ml at behnel.de Sun Feb 17 01:54:36 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 17 Feb 2008 07:54:36 +0100 Subject: Validating cElementTrees with lxml In-Reply-To: References: Message-ID: <47B7DA2C.8080704@behnel.de> Hi, Ryan K wrote: > If I have a cElementTree.ElementTree (or the one from the Standard > Library), can I use lxml's validation features on it since it > implements the same ElementTree API? Not directly. lxml and cElementTree use different tree models internally, so you can't just apply C-implemented features of one to the other. Any reason you can't just use lxml /instead/ of cElementTree? In case you really want to combine both: to validate the tree, you only need to create an lxml tree from your ElementTree in a one-way operation, which is easy, as this can be done through the (identical) API. Just create a new lxml Element and then traverse the ElementTree recursively, create a new SubElement for each child you find, and set its text, tail and attrib properties. Something like this might work (though untested): class TreeMigrator(object): def __init__(ET_impl_from, ET_impl_to): self.Element = ET_impl_to.Element self.SubElement = ET_impl_to.SubElement def copyChildren(self, from_parent, to_parent): for from_child in from_parent: tag = from_child.tag if not isinstance(tag, basestring): # skip Comments etc. continue to_child = self.SubElement( to_parent, tag, **from_child.attrib) to_child.text = child.text to_child.tail = child.tail self.copyChildren(from_child, to_child) def __call__(self, from_root): tag = from_root.tag to_root = self.Element(tag, **from_root.attrib) to_root.text = from_root.text to_root.tail = from_root.tail if isinstance(tag, basestring): # skip Comments etc. self.copyChildren(from_root, to_root) return to_root Feel free to finish it up and send it back to the list. :) Stefan From mensanator at aol.com Wed Feb 13 14:11:13 2008 From: mensanator at aol.com (mensanator at aol.com) Date: Wed, 13 Feb 2008 11:11:13 -0800 (PST) Subject: Regular Expression for Prime Numbers (or How I came to fail at them, and love the bomb) References: <85ca4615-c51f-4aab-b400-f3f80056faec@l32g2000hse.googlegroups.com> Message-ID: On Feb 13, 12:53?pm, Carsten Haese wrote: > On Wed, 2008-02-13 at 10:40 -0800, mensana... at aol.com wrote: > > But why doesn't it work when you make that change? > > I can't answer that question, because it *does* work when you make that > change. Well, the OP said the function was returning None which meant no match which implies None means composite for the given example 2. If None was supposed to mean prime, then why would returing None for 2 be a problem? But isn't this kind of silly? ## 3 None ## 4 <_sre.SRE_Match object at 0x011761A0> ## 5 None ## 6 <_sre.SRE_Match object at 0x011761A0> ## 7 None ## 8 <_sre.SRE_Match object at 0x011761A0> ## 9 <_sre.SRE_Match object at 0x011761A0> ## 10 <_sre.SRE_Match object at 0x011761A0> ## 11 None ## 12 <_sre.SRE_Match object at 0x011761A0> ## 13 None ## 14 <_sre.SRE_Match object at 0x011761A0> ## 15 <_sre.SRE_Match object at 0x011761A0> ## 16 <_sre.SRE_Match object at 0x011761A0> ## 17 None ## 18 <_sre.SRE_Match object at 0x011761A0> ## 19 None > > -- > Carsten Haesehttp://informixdb.sourceforge.net From paul.hermeneutic at gmail.com Sat Feb 16 11:59:18 2008 From: paul.hermeneutic at gmail.com (Paul Watson) Date: Sat, 16 Feb 2008 10:59:18 -0600 Subject: SOAP strategies Message-ID: <1203181157.2649.11.camel@localhost.localdomain> What are the reasonable current day choices and best bets for the future when doing SOAP programming in Python? SOAP batteries do not appear to be in the standard Python distribution. Most of the SOAP related information I have been able to find on the web is from 2001-2002. I am not sure if some packages are still maintained. Most of this is old news. http://soapy.sourceforge.net/ http://pywebsvcs.sourceforge.net/ (SOAPpy) and what is the relation of this to ZSI http://www.intertwingly.net/stories/2002/12/20/sbe.html http://www.ibm.com/developerworks/library/ws-pyth5/ http://www.opensourcetutorials.com/tutorials/Server-Side-Coding/Python/python-soap-libraries/page1.html http://www.gossamer-threads.com/lists/python/python/619251 This is current, but is this a long term strategy or a short term tactic? From j.foster.davis at gmail.com Thu Feb 21 02:01:42 2008 From: j.foster.davis at gmail.com (Jacob Davis) Date: Wed, 20 Feb 2008 23:01:42 -0800 Subject: usenet problem Message-ID: Hi. I am a newbie to usenet. I am using mac and have downloaded a free usenet client, "MT-NewsWatcher". I put in comp.lang.python but it says that it cannot get the address of the news server host. My config says it is trying on port 119. Thanks for any help. Jake From xnews2 at fredp.lautre.net Tue Feb 19 12:41:03 2008 From: xnews2 at fredp.lautre.net (Fred Pacquier) Date: 19 Feb 2008 17:41:03 GMT Subject: ANN: Phatch = PHoto bATCH processor and renamer based on PIL References: <15f9eaeb-8d02-4090-922e-97a65c20fe51@e23g2000prf.googlegroups.com> Message-ID: Steve Holden said : > Perhaps you could put a link to the source on the Windows instalL page? > I don't mind being a second-class citizen, but it's annoying to have to > jump around like that. I'm interested too, and was also wondering if Phatch is as full-featured unders Windows as under Linux, specifically the EXIF/IPTC functions made available through pyexiv2 : exiv2 itself seems to discriminate between the two, the Windows package only has the executable, not the library. -- YAFAP : http://www.multimania.com/fredp/ From parvini_navid at yahoo.com Sun Feb 3 08:04:14 2008 From: parvini_navid at yahoo.com (Navid Parvini) Date: Sun, 3 Feb 2008 05:04:14 -0800 (PST) Subject: scope Message-ID: <438712.29654.qm@web54505.mail.re2.yahoo.com> Dear All, I have the following two methods in a module. I cannot put them in a class, as the code is a complicated one. def a(num): found = num in Numlist print found def b(): scop = {} scop['Numlist'] = [1,2,3] scop['a'] = a exec("a(3)",scop) How can I access the "Numlist" inside the method a, without using classes or defining Numlist as GLOBAL? I prefer using scops in this problem. Is there a way? Thank you very much, Navid --------------------------------- Looking for last minute shopping deals? Find them fast with Yahoo! Search. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bignose+hates-spam at benfinney.id.au Wed Feb 20 20:09:45 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 21 Feb 2008 12:09:45 +1100 Subject: The big shots References: <89d15587-e8de-444c-b240-4a10305146e0@e23g2000prf.googlegroups.com> <3c035ede-d98b-4adc-bde4-5a918bd04dd8@h25g2000hsf.googlegroups.com> <586b3c9c-6b8b-4fce-9307-4984b857276a@s37g2000prg.googlegroups.com> <87ir0jgor9.fsf@benfinney.id.au> <4f3c8b44-9ba6-4901-a0fe-4f2de0ce0b2b@q70g2000hsb.googlegroups.com> Message-ID: <87ejb7glnq.fsf@benfinney.id.au> castironpi at gmail.com writes: > On Feb 20, 6:02?pm, Ben Finney > wrote: > > For what it's worth, I've found none of your threads in the last > > few weeks to make much sense at all, because of unclear and > > incoherent writing. On that basis, I dismiss them before trying to > > re-read them, because I don't want to spend my time trying to find > > sense in them that may not be there at all. > > How do I "bake" this idea? [loads of further verbiage apparently > nothing to do with what Ben Finney wrote] Here's another example of the above point. I've no idea what the context is supposed to be of all the stuff you just wrote in your message. It's also written in a fractured style that makes it very difficult to follow. Hence, I tune out. > Are further problems a) miscommunication or b) absence of content? > If Holden and Genellina don't follow, that's a strong sign that the > structure of my proposals is really bad, even if there's a good > thing behind it. You just have to solve (a) before you solve (b), > which makes devoting resources to (a) a little preliminary. Agreed. I'll wait until you have better results from improving communication before I devote further resources to your messages. -- \ "It's a good thing we have gravity or else when birds died | `\ they'd just stay right up there. Hunters would be all | _o__) confused." -- Steven Wright | Ben Finney From gherron at islandtraining.com Mon Feb 25 11:49:48 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 25 Feb 2008 08:49:48 -0800 Subject: String compare question In-Reply-To: <496954360802250836u162eeb49tfac382c6ef2f96a7@mail.gmail.com> References: <496954360802250836u162eeb49tfac382c6ef2f96a7@mail.gmail.com> Message-ID: <47C2F1AC.7030004@islandtraining.com> Robert Dailey wrote: > Hi, > > Currently I have the following code: > > > ignored_dirs = ( > r".\boost\include" > ) You expect this is creating a tuple (or so I see from your "in" test in the following code), but in fact the parenthesis do *not* make a tuple. If you look at ignored_dirs, you'll find it's just a string. It's the presence of commas that signam a tuple. You need ignored_dirs = ( r".\boost\include", # It's that comma that makes this a tuple. ) > > if __name__ == "__main__": > # Walk the directory tree rooted at 'source' > for root, dirs, files in os.walk( source ): > if root not in ignored_dirs: > CopyFiles( root, files, ".dll" ) > else: > print root > > > Specifically take a look at the if condition checking if a string is > inside of ignored_dirs. Of course this will only do substring > searches, however I want to perform an exact match on this string. Is > there anyway of doing this? Thanks. From grante at visi.com Tue Feb 19 23:29:42 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 20 Feb 2008 04:29:42 -0000 Subject: The big shots References: <89d15587-e8de-444c-b240-4a10305146e0@e23g2000prf.googlegroups.com> <7xmypx61z6.fsf@ruckus.brouhaha.com> <823e82d6-4faf-453f-9330-a34c262c2f52@e25g2000prg.googlegroups.com> <13rmlqa9hc2344b@corp.supernews.com> <52dba0a7-6e8d-410a-b15b-276b90395fb5@i12g2000prf.googlegroups.com> Message-ID: <13rnb5moderbde8@corp.supernews.com> On 2008-02-19, castironpi at gmail.com wrote: > What is a a homile? It's a misspelling of homily. :) -- Grant Edwards grante Yow! It's hard being at an ARTIST!! visi.com From darcy at druid.net Tue Feb 26 12:12:22 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 26 Feb 2008 12:12:22 -0500 Subject: How about adding rational fraction to Python? In-Reply-To: References: <97f30679-483d-4751-9a6e-0858b36eb426@d4g2000prg.googlegroups.com> <649ac8a9-ae09-4e9b-85c2-f37043af21fd@28g2000hsw.googlegroups.com> <0d1955fc-762c-44e1-a5d8-372c71458455@p25g2000hsf.googlegroups.com> <36204e6f-0d82-449b-8ca5-c819ace9a55a@p73g2000hsd.googlegroups.com> <9503b14b-7bd5-42b4-b3f7-673d0ebd7feb@c33g2000hsd.googlegroups.com> <602ac27c-4aaa-49b2-bee2-1e0e0c705983@i7g2000prf.googlegroups.com> Message-ID: <20080226121222.5a60e19b.darcy@druid.net> On Tue, 26 Feb 2008 09:01:57 -0800 Jeff Schwab wrote: > Or Jo thinks // is a typo, and helpfully "fixes" it. Exactly. "Programmers" who use a language without learning it are apt to do anything. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From lizhongan at gmail.com Sun Feb 24 19:12:59 2008 From: lizhongan at gmail.com (zaley) Date: Sun, 24 Feb 2008 16:12:59 -0800 (PST) Subject: Is there a open souce IDE writen by C( C++) or partly writen by C( C++)? References: <42a838b9-2023-4cbf-bc53-e7ac5f4accbc@i7g2000prf.googlegroups.com> <47BE6D27.7000305@behnel.de> <47bee4d6$0$15901$edfadb0f@dtext01.news.tele.dk> Message-ID: <3c7c8149-2407-45a2-be67-d59b080f8ee4@s13g2000prd.googlegroups.com> On 2?25?, ??6?34?, Ricardo Ar?oz wrote: > zaley wrote: > > On Feb 24, 6:48 am, Ricardo Ar?oz wrote: > >> Lie wrote: > >>> On Feb 23, 4:02 pm, zaley wrote: > >>>> On Feb 22, 11:06 pm, "Jesper" wrote: > >>>>> Give PyScripter fromhttp://www.mmm-experts.com/atry > >>>>> It is for Windows, though it is written in Delphi and not in C/C++ > >>>>> /Jesper > >>>>> "zaley" skrev i en meddelelsenews:c1528422-5db2-4193-919b-b0a851d973f4 at b29g2000hsa.googlegroups.com... > >>>>> Of course, python scripts debugger > >>>>> On 2??22??, ????3??22??, zaley wrote: > >>>>>> My project need a simple scripts debugger . I hope I can find > >>>>>> something instructive > >>>>>> Stefan Behnel ?????? > >>>>>>> zaley wrote: > >>>>>>>> Is there a open souce IDE writen by C( C++) or partly writen by C( C+ > >>>>>>>> +)? > >>>>>>> Tons of them. What do you want to do with it? > >>>>>>> Stefan- Hide quoted text - > >>>>> - Show quoted text - > >>>> But PyScripter is not a open source project > >>> Am I correct to say that the reason why you wanted an open source C++ > >>> IDE is because you wanted the freedom to modify your own programming > >>> environment? > >> >From the "About" window in PyScripter : > > >> """ > >> A freeware, open source Python scripter integrated > >> development environment created with the ambition to bring to > >> the Python community the quality and functionality available in > >> commercial IDEs available for other languages. > >> """ > > >> So I think we could say PyScripter IS an open source project.- Hide quoted text - > > >> - Show quoted text - > > > Really, what I want to do is that scripts can be executed step by > > step . > > I know By "Py_Runstring" clauses in main function can executed by > > step . > > But I can't know how to step into a function and how to step in a > > function. > > So I hope I can find something helpful in open source IDE for python. > > Exactly so. PyScripter does it easy, besides you can have in different > tabs all the modules of your application. You just hit the run button > and your program runs, you hit the debug button and you start going step > by step. It's free, easy to install, just give it a try and if you don't > like it just trash it. I just want to know how to realize it in my program !! From paul at boddie.org.uk Sun Feb 3 18:31:49 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 3 Feb 2008 15:31:49 -0800 (PST) Subject: Is it explicitly specified? References: <60lqmqF1rkeiqU1@mid.individual.net> <60m2qnF1rgp7fU1@mid.uni-berlin.de> <9d3145c0-1128-4f7e-a9b5-2789f9231f34@1g2000hsl.googlegroups.com> Message-ID: On 3 Feb, 16:41, mario wrote: > > In one case, the collection attributes a specific meaning to > attr=None, but the actual default for attr is something else. However, > if an object explicitly wants to state that his attr=None (that is a > valid value, and has specific meaning) I would like to use that as > value, but if no value is supplied for attr by the object, then I > would like to use the default value from the collection. I don't know whether I can offer much better advice than others, but I have noticed that a lot of my own code has moved in the direction of not having specific default values in function/method signatures. So, instead of this... def f(x=123): ... ...I have this: def f(x=None): if x is None: x = 123 Of course, you can shorten this to "x = x or 123", but consider what might happen if x is given as 0. As for exposing the defaults, it's always possible to define them elsewhere, something which is very feasible with classes: class X: default = 123 def f(self, x=None): if x is None: x = self.default # or X.default The main reason for avoiding preset defaults has been to allow unspecified values to "cascade" through several levels of functions, if required, with the default being chosen at the most appropriate place. Now, your problem would involve explicitly specified values of None which would inadvertently cause the default to be used in the above cases. As others have said, a "sentinel" or special value would probably be a good replacement for None: class NotSetType: pass NotSet = NotSetType() # or just use object() def f(x=NotSet): if x is NotSet: x = 123 You could even explicitly pass NotSet to the function, too. Paul From castironpi at gmail.com Sun Feb 17 15:43:01 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 17 Feb 2008 12:43:01 -0800 (PST) Subject: call 'the following function' using decorators References: <4881cc78-85cc-4cf4-8e70-8089374d08f9@v17g2000hsa.googlegroups.com> <2050a2fa-0026-4923-9e5f-d3b4b53e4959@e25g2000prg.googlegroups.com> Message-ID: <6316f9f0-b21a-4edf-bcea-0c070d8f1867@d5g2000hsc.googlegroups.com> On Feb 15, 7:54?pm, castiro... at gmail.com wrote: > > > > > I assert it's easier to write: > > > > > > start_new_thread( this_func ) > > > > > def thrA(): > > > > > ? ? normal_suite() > > > > > > than > > > > > > def thrA(): > > > > > ? ? normal_suite() > > > > > start_new_thread( thrA ) > > > > > > If you don't, stop reading. > > Nothing beats if forkthread(): but what are the chances of getting it > in Python? AIR, as I recall, the SML equivalent is: var TM: thread_manager in def forkthread(): TM.add( True, False ) in if forkthread() thing_to_do() else other_thing_to() where programs can refer to a thread_manager along with a memory, which yes, is even in a functional language, well-defined. thread_manager altertantely beta-reduces one expression at a time in round-robin succession. thread_manager.add duplicates the current expression, and evaluates to True in one and False in the other. From steve at REMOVE-THIS-cybersource.com.au Thu Feb 14 10:47:16 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 14 Feb 2008 15:47:16 -0000 Subject: InstanceType tests in Python-3.0 References: Message-ID: <13r8ok4l36kr6af@corp.supernews.com> On Thu, 14 Feb 2008 15:26:08 +0000, Robin Becker wrote: > I'm in the process of porting some code. I have 2.x code that looks like > this > > t = type(e) > if t==InstanceType: > return f0(e) > elif t in (float,int): > return f1(e) > else: > return str(e) What happens if e is an instance of a subclass of int, or str? I'd write the above like this: if isinstance(e, type.InstanceType): # old-style classes don't exist in Python 3 return f0(e) elif isinstance(e, (float, int)): return f1(e) else: return str(e) Now all you have to do is work out what to do with new-style classes... > In python 3.0 everything has been unified and people say use attributes > to tell what should be done in such a branch. Well, you know what people say about people who listen to everything people say. What do you mean "everything" has been unified? What do you mean "use attributes to tell what should be done"? > However, this is the real world No, this is SPARTA!!! (Sorry, I couldn't resist. And I didn't even like the movie.) > and this code is fairly complex. Originally we had a distinction > between user defined class instances and those of the builtins like > float, int, str etc etc. Is there any way for me to tell if an object is > an instance of a used defined class which can then be tested further > perhaps? Why do you care if it is a user-defined class or not? What are you actually trying to accomplish? What's your aim in doing this testing? -- Steven From grante at visi.com Fri Feb 8 10:31:46 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 08 Feb 2008 15:31:46 -0000 Subject: OT: Star Wars and parsecs [was Re: Why not a Python compiler?] References: <28eead2f-a40c-414b-bd3d-a941f8a851a2@d70g2000hsb.googlegroups.com> <7da40f42-f64f-4939-a0dc-d24d1ff85f2d@v4g2000hsf.googlegroups.com> <13qjktdbe76da00@corp.supernews.com> <13qmp56btnr55a4@corp.supernews.com> <13qmtqebm4t6979@corp.supernews.com> <13qo0rkr7osv792@corp.supernews.com> Message-ID: <13qotf2mgpvkoac@corp.supernews.com> On 2008-02-08, Dennis Lee Bieber wrote: > A Parsec is a fixed value (which, admittedly, presumes the culture > developed a 360degree circle broken into degrees => minutes => > seconds... or, at least, some units compatible with the concept of an > "arc second", like 400 grads of, say, 100 "minutes", each of 100 > "seconds") It also presumes a standard diamter of that circle. -- Grant Edwards grante Yow! Are you the at self-frying president? visi.com From see.signature at no.spam Mon Feb 4 06:20:29 2008 From: see.signature at no.spam (Eric Brunel) Date: Mon, 04 Feb 2008 12:20:29 +0100 Subject: What should I use under *nix instead of freeze? References: <7498f946-9ea6-48fe-a509-c80cf425af11@j78g2000hsd.googlegroups.com> Message-ID: On Sat, 02 Feb 2008 00:08:21 +0100, Mike Kent wrote: > In a comment Guido made on a recent bug report for the 'freeze' > utility, he stated: > > "I think nobody really cares about freeze any more -- it isn't > maintained." > > That being the case, what is the preferred/best replacement for freeze > on a *nix platform? I'm looking for something that, like freeze, > turns my application into a single-file executable, of the smallest > size possible, that can be executed on a machine with no Python > installation or development system. Never used it, but it seems cx_Freeze (http://python.net/crew/atuining/cx_Freeze/) does just that... Don't know if it's maintained anymore, but versions are available for the latest Python version (2.5). HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From jorgen.maillist at gmail.com Thu Feb 7 11:16:05 2008 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Thu, 7 Feb 2008 17:16:05 +0100 Subject: Small problem executing python script as shortcut Message-ID: <11e49df10802070816k65544been5ad199bbb75353bb@mail.gmail.com> Hi all, This is slightly OT but it drives me nuts. Whenever I create a shortcut in the start menu (in Windows) of a python script, it will only execute it when the path where the script resides in contains no spaces. For example; d:\src\app\app.py If I drag that to the Start Menu it can be executed fine. Whenever I distribute my app and the path will become: "c:\program files\app\app.py" Windows will make spaces itself inside the shortcut so I guess it realizes that it needs to execute the full string but probably somewhere when resolving the app to execute the script with, the double quotes get lost and the python interpreter (I use ActiveState as my Python bundle) will only see "c:\program" as the first part and doesn't pick up the latter. I know I can write a batch script that runs the python script, but since it is a wxPython app, I want to launch a *.pyw to suppress the dos box. However as it seems now there is no way to create a shortcut under windows to launch a python script when the directory contains spaces in the name. Does anyone know a solution? I would like to distribute my app both with py2exe (no problems there) but also as source only version so people can adjust the code if they wish. Regards, - Jorgen From aantny at gmail.com Wed Feb 6 06:22:09 2008 From: aantny at gmail.com (Natan Yellin) Date: Wed, 6 Feb 2008 03:22:09 -0800 (PST) Subject: Retreiving objects from other processes Message-ID: <19b182bc-b40d-478c-96b7-6894ab3072a9@v67g2000hse.googlegroups.com> Hello, Sorry if this is a stupid question... I have some experience with C but very little with Python. I'd like to have one python program retrieve a reference or copy of an object from another python process on the same computer. I know I can use RPyC, but that seems like overkill. Is there simpler way of doing it? Thanks in advance, Natan From Lie.1296 at gmail.com Fri Feb 29 20:29:32 2008 From: Lie.1296 at gmail.com (Lie) Date: Fri, 29 Feb 2008 17:29:32 -0800 (PST) Subject: How about adding rational fraction to Python? References: <13scs8k1kh9nk81@corp.supernews.com> <13see4t3s23pn59@corp.supernews.com> <9cd8f360-da6b-4a9d-a21c-c93adfd5cc20@i29g2000prf.googlegroups.com> Message-ID: <938df38f-40b2-4d06-beee-4b0bf2b195fa@e6g2000prf.googlegroups.com> On Feb 28, 10:00 am, Paul Rubin wrote: > More examples: > > x = 1 > y = len(s) + x > > => ok, decides that x is an int > > x = 1 > y = x + 3.0 > > => ok, decides that x is a float > > x = 1 > y = x + 3.0 > z = len(s) + x > > => forbidden, x cannot be an int and float at the same time. > > > I am so glad you're not the designer of Python. > > This is how Haskell works and I don't notice much complaints about it. Ok, that means the line "y = x + 3.0" have a side effect of "x = float(x)"? I think I would say that is an implicit behavior. On Feb 28, 11:22 pm, "D'Arcy J.M. Cain" wrote: > > You people can't tell the difference between "obvious" and "learned > > conventions that came about because in limitations in the hardware at > > the time". Nobody would have come up with a silly rule like "x op y > > must always have the same type as x and y" if computer hardware had > > been up to the task when these languages were created. > > What makes you say they weren't? Calculating machines that handled > floating point are older than Python by far. > But much younger than the first programming language (if it could be called as a language) that set the convention of int op int should result in int 'cause our hardware can't handle floats. On Feb 29, 6:15 am, Paul Rubin wrote: > Can you name an example of a calculating machine that both: > 2) says 1/2 = 0.5 ? Any pocket calculator to scientific calculator. Except perhaps my calculator which is fraction scientific calculator where it stores 1/2 as rational and have another division operator for 1/2 == 0.5 From cwitts at gmail.com Tue Feb 5 14:27:36 2008 From: cwitts at gmail.com (Chris) Date: Tue, 5 Feb 2008 11:27:36 -0800 (PST) Subject: Broke my IDLE! References: <1e6ec8dc-3fa4-4e75-86c1-26852ea30a65@n20g2000hsh.googlegroups.com> Message-ID: <48a7d2e5-88f3-4760-9eac-3ae728ad3e13@v4g2000hsf.googlegroups.com> On Feb 5, 7:05 pm, "Adam W." wrote: > Tried running IDEL from the command prompt to get this: > > Traceback (most recent call last): > File "c:\Python25\Lib\idlelib\idle.pyw", line 21, in > idlelib.PyShell.main() > File "c:\Python25\lib\idlelib\PyShell.py", line 1404, in main > shell = flist.open_shell() > File "c:\Python25\lib\idlelib\PyShell.py", line 275, in open_shell > self.pyshell = PyShell(self) > File "c:\Python25\lib\idlelib\PyShell.py", line 813, in __init__ > OutputWindow.__init__(self, flist, None, None) > File "c:\Python25\lib\idlelib\OutputWindow.py", line 16, in __init__ > EditorWindow.__init__(self, *args) > File "c:\Python25\lib\idlelib\EditorWindow.py", line 125, in > __init__ > self.apply_bindings() > File "c:\Python25\lib\idlelib\EditorWindow.py", line 900, in > apply_bindings > text.event_add(event, *keylist) > File "c:\Python25\lib\idlelib\MultiCall.py", line 345, in event_add > widget.event_add(self, virtual, seq) > File "c:\Python25\lib\lib-tk\Tkinter.py", line 1357, in event_add > self.tk.call(args) > _tkinter.TclError: extra characters after detail in binding > > What do I need to edit and change? Python25\Lib\idlelib\config-keys.def From Graham.Dumpleton at gmail.com Sun Feb 3 18:40:03 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Sun, 3 Feb 2008 15:40:03 -0800 (PST) Subject: apache/mod_wsgi daemon mode References: Message-ID: <0676dd01-1284-43e8-bbc1-223500f88c4b@v29g2000hsf.googlegroups.com> On Feb 4, 10:33 am, Scott SA wrote: > On 2/3/08, Brian Smith (br... at briansmith.org) wrote: > >Scott SA wrote: > >> I am trying to configure mod_wsgi to run in daemon mode with > >> Apache. I can easily get it to run 'normally' under Apache > >> but I obtain permission errors _or_ process-failures in > >> daemon mode. Specifically: > > >> ... (13)Permission denied: mod_wsgi (pid=26962): Unable > >> to connect > >> to WSGI daemon process '' on > >> '/etc/httpd/logs/wsgi.26957.0.1.sock' after multiple attempts. > > ... > > I had previoiusly done what I _thought_ was a good job of searching the wsgi mailing list (really!). A reworking of my google search parameters finally yeildd a helpful thread: > > > > The problem was WSGI trying to create its .sock file in /var/log/httpd but failing and therefore not running at all. The user I had specified did not have enough permissions to do so (part of the point _of_ running in daemon mode, LOL). Oddly, I had attempted to grant the permissions for the user but see now there was an error in how I did that... oops. > > By adding the following to my config: > > WSGISocketPrefix /tmp/wsgi Also documented in: http://code.google.com/p/modwsgi/wiki/ConfigurationIssues Since you have given a real live example error message from logs for when it goes wrong, I'll be able to include this in the documentation. That may make it easier for others to find that page when they do a Google search. At the moment the page only mentioned that you would get a '503 Service Temporarily Unavailable' response in browser. Graham > We now have successss! > > So my config now looks like: > > WSGISocketPrefix /tmp/wsgi > > > ServerName host.domain.com > > WSGIDaemonProcess user= group= threads=10 \ > maximum-requests=500 > > WSGIScriptAlias /something /path/to/